/*
Description: Write a function canSum(targetSum, numbers) that takes in a
targetSum and an array of numbers as arguments.
The function should return a boolean indicating whether or not it is possible
to generate the targetSum using numbers from the array
You may use an element of the slice as many times as needed.
Assume that all input numbers are non-negative.
*/
package main
import "fmt"
func canSum(targetSum int, numbers ...int) bool {
if targetSum == 0 {
return true
}
if targetSum < 0 {
return false
}
for index := 0; index < len(numbers); index++ {
if canSum(targetSum-numbers[index], numbers...) == true {
return true
}
}
return false
}
//var memo = map[int]bool{} //Getting wrong values due to shared function scope from package scope
func memo_canSum(targetSum int, numbers ...int) bool {
memo := map[int]bool{} //Defeats dp func since we continue to reinitialize during recursive calls
if _, exists := memo[targetSum]; exists {
return memo[targetSum]
}
if targetSum == 0 {
return true
}
if targetSum < 0 {
return false
}
for index := 0; index < len(numbers); index++ {
if memo_canSum(targetSum-numbers[index], numbers...) == true {
memo[targetSum] = true
return memo[targetSum]
}
}
memo[targetSum] = false
return false
}
func main() {
//Non-Dp Solution
fmt.Println(canSum(21, 2, 4, 8))
fmt.Println(canSum(80, 2, 4, 8))
fmt.Println(canSum(300, 7, 14))
//Dp Solution
fmt.Println(memo_canSum(21, 2, 4, 8))
fmt.Println(memo_canSum(80, 2, 4, 8))
fmt.Println(memo_canSum(300, 7, 14))
}
So I've ran into an issue while programming with golang, if i declare my memoized map outside of my function then all function calls share the same map and it leads to error's with the results. If i declare the map inside the function then each recursive call reinitializes the map. Is there any way to make the map a static local variable?