conned
conned

Reputation: 13

Find the most common element in a string array GO

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

Upvotes: 0

Views: 920

Answers (2)

aMike
aMike

Reputation: 937

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

Upvotes: 0

bruceg
bruceg

Reputation: 2513

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

Upvotes: 1

Related Questions