I have a strange problem. I was playing with Go and found some very strange behaviour that I couldn't figure it out.
When I run the findMatchingSum
function, it searches the expected sum by if sum is bigger I decrement the last index by 1, if bigger, increment the first index by one.
However, when I debug the code, it hits first if statement and should return true, however instead it directly goes and runs last else if statement.
The confusion starts here. On the 3rd iteration it hits the if statement goes into that block but does not quit the function.
Here is the code;
package main
import "fmt"
var arr = []int{1,2,4,4}
func main() {
s := findMatchingSum(arr, 8, len(arr) - 1, 0)
fmt.Println(s)
}
func findMatchingSum(arr []int, sum , last, first int ) bool {
if arr[first] + arr[last] == sum {
return true
} else if arr[first] + arr[last] > sum {
findMatchingSum(arr, sum, last - 1, first)
} else if arr[first] + arr[last] < sum {
findMatchingSum(arr, sum, last, first + 1)
}
return false
}
You forgot to "return" from the else-if branches. This should work:
func findMatchingSum(arr []int, sum , last, first int ) bool {
if arr[first] + arr[last] == sum {
return true
} else if arr[first] + arr[last] > sum {
return findMatchingSum(arr, sum, last - 1, first)
} else if arr[first] + arr[last] < sum {
return findMatchingSum(arr, sum, last, first + 1)
}
return false
}
If you don't do this, the third branch will be executed, but the function won't exit - it will jump to the next instruction, which is "return false".