algorithmswithgo.com
algorithmswithgo.com copied to clipboard
Getting different results in std_demo
I'm using go1.16.4 in windows 10.
when I try:
go run main.go < input.txt im getting
0 5 0 4
but according to the video, it should be: 5 4 11 33
im using the following GCD function:
for { if b == 0 { return a } a, b = b, a%b }
all the test cases passed for that GCD function,
can someone explain to me, what is going on?
thanks,
If I clone the repo, replace the GCD function with your code:
package module01
func GCD(a, b int) int {
for {
if b == 0 {
return a
}
a, b = b, a%b
}
}
And then run go run module01/std_demo/main.go < module01/std_demo/input.txt
from the root directory, I get the following output:
5
4
11
33
This suggests that something isn't wrong with your code, but something is wrong somewhere else. My best guess is that you are on a different OS or something else is causing your code to not work. On possible answer is that newlines are treated slightly different in your OS (are you on Windows?) and the following might work better:
// std_demo/main.go
func main() {
var n int
fmt.Scanf("%d", &n)
for i := 0; i < n; i++ {
var a, b int
fmt.Scanf("%d %d\n", &a, &b) // < this is the change
gcd := module01.GCD(a, b)
fmt.Println(gcd)
}
}
If that doesn't work, I still suspect the issue is related to something along these lines, as the gcd_test.go file covers plenty of cases to suggest your code is working.
yes, I'm on windows 10, unfortunately, the change
fmt.Scanf("%d %d\n", &a, &b)
didn't work, but I'll keep digging. Let me do some homework, I'll get back with answers.
btw, amazing course!