Home > Mobile >  Find the most common element in a string array GO
Find the most common element in a string array GO

Time:12-23

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

CodePudding user response:

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

CodePudding user response:

if N > winner {
    winner = N
    windEL = "Noord"
}

CodePudding user response:

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

  •  Tags:  
  • go
  • Related