0

i'm fairly new to golang and im having trouble finding the most common string in an array (Windrichting). it should be N but my output gives me W (it always gives me the last string so Windrichting[6]. Can someone help?

this is my code:

package main

import "fmt"

func main() {
    Windrichting := [7]string{"N", "N", "N", "N", "O", "Z", "W"}

windEL, winner := Mostcommon(Windrichting)

fmt.Printf("Mostcommon windrichting: %s\n", windEL)
fmt.Printf("Komt %d x voor\n", winner)
}


func Mostcommon(Windrichting [7]string) (windEL string, winner int) {
    var N int
    var O int
    var Z int
    var W int
    Windrichtingbase := [4]string{"N", "O", "Z", "W"}

for _, v := range Windrichting {
    switch v {
    case Windrichtingbase[0]:
        N++
        if N > winner {
            N = winner
            windEL = "Noord"
        }
    case Windrichtingbase[1]:
        O++
        if O > winner {
            O = winner
            windEL = "Oost"
        }
    case Windrichtingbase[2]:
        Z++
        if Z > winner {
            Z = winner
            windEL = "Zuid"
        }
    case Windrichtingbase[3]:
        W++
        if W > winner {
            W = winner
            windEL = "West"
        }
    }
}
return windEL, winner
}

output

2 Answers 2

1

winner is always 0 and you never update it. then after incrementing your direction variables (N, O, Z and W), you immediately overwrite them with the zero value stored in winner. You need to reverse the order of the assignment.

Like in this change: https://go.dev/play/p/VaJgZcijFdh

Note also, that capitalized variables in Go mean they're exported

Sign up to request clarification or add additional context in comments.

1 Comment

Solid answer. Kind of off topic but I would also add that it is probably a good idea to make the Windrichting parameter a slice []string rather than an array [7]string. Unless you expect the input data list will always have a length of 7.
0

Here's an alternate implementation. It uses a histogram to collect the number of times a word appears. It then steps through the histogram to find the most common word. Nothing is hard-coded.

https://go.dev/play/p/wTFvNaPRP6B

1 Comment

Had the same thought but it doesn't include the output Dutch text OP wanted. So maybe this plus an "enum" for converting from rune to the Dutch strings? I believe the Dutch text may have been his reason for using the switch instead of this implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.