英文:
Find the most common element in a string array GO
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我对Go语言还比较新手,我在一个数组(Windrichting)中找不到最常见的字符串。应该是"N",但我的输出却是"W"(它总是给我最后一个字符串Windrichting[6])。有人可以帮忙吗?
这是我的代码:
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 {
winner = N
windEL = "Noord"
}
case Windrichtingbase[1]:
O++
if O > winner {
winner = O
windEL = "Oost"
}
case Windrichtingbase[2]:
Z++
if Z > winner {
winner = Z
windEL = "Zuid"
}
case Windrichtingbase[3]:
W++
if W > winner {
winner = W
windEL = "West"
}
}
}
return windEL, winner
}
英文:
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
}
答案1
得分: 1
赢家始终为0,你从未更新它。然后,在增加方向变量(N、O、Z和W)之后,你立即用存储在赢家中的零值覆盖它们。你需要改变赋值的顺序。
就像这个变化一样:https://go.dev/play/p/VaJgZcijFdh
还要注意,Go中的大写变量表示它们是可导出的。
英文:
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
答案2
得分: 0
这是一个替代实现。它使用直方图来收集单词出现的次数。然后通过直方图遍历来找到最常见的单词。没有硬编码。
https://go.dev/play/p/wTFvNaPRP6B
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论