如何在 go 中创建地图并查找重复项
How to create a map and find duplicates in go
我是新手,不知道如何完成这项任务:
Write a program that, in the first line, reads from the standard input
the number of consecutive digits in the range [1; 9], which will then
be loaded into the array. Then prints the number of repeated instances
of the specified array value to the standard output.
Input:
7
1 1 2 2 1 3 5
Output:
1: 3
2: 2
3: 1
5: 1
这个任务我已经完成一半了,但是我不知道如何通过地图进行重复跟踪
func main() {
var numbers int
fmt.Println("num: ")
fmt.Scan(&numbers)
var numArr int
var i = 1
arr := make([]int, 0)
if numbers <= 9 {
for ; i <= numbers; i++ {
fmt.Println("numArr: ")
fmt.Scan(&numArr)
if numArr < 9 {
arr = append(arr, numArr)
} else {
fmt.Println("sorry write the number up to 9")
break
}
}
} else {
fmt.Println("Max Numbers = 9")
}
fmt.Println(arr)
m := make(map[int]int)
for key, v := range arr {
}
您似乎想用 map[Value From File]Count
填充地图。因此,每个收到的不同数字都会有一个条目,地图中保存的值将是该值(键)被看到的次数。填充此类地图的简单方法是:
for _, v := range arr {
m[v]++
}
Playground。请注意,map
是无序的,因此您可能需要在输出结果之前对其进行排序。
注意:您可以通过 aligning the happy path to the left edge 即
来简化代码(并修复一个细微的错误)
if numbers > 9 {
fmt.Println("Max Numbers = 9")
return // Important - otherwise we will still try to find duplicates in the 'large' slice
}
// Do stuff that should happen when we have 9 or fewer ints
我是新手,不知道如何完成这项任务:
Write a program that, in the first line, reads from the standard input the number of consecutive digits in the range [1; 9], which will then be loaded into the array. Then prints the number of repeated instances of the specified array value to the standard output.
Input:
7
1 1 2 2 1 3 5
Output:
1: 3
2: 2
3: 1
5: 1
这个任务我已经完成一半了,但是我不知道如何通过地图进行重复跟踪
func main() {
var numbers int
fmt.Println("num: ")
fmt.Scan(&numbers)
var numArr int
var i = 1
arr := make([]int, 0)
if numbers <= 9 {
for ; i <= numbers; i++ {
fmt.Println("numArr: ")
fmt.Scan(&numArr)
if numArr < 9 {
arr = append(arr, numArr)
} else {
fmt.Println("sorry write the number up to 9")
break
}
}
} else {
fmt.Println("Max Numbers = 9")
}
fmt.Println(arr)
m := make(map[int]int)
for key, v := range arr {
}
您似乎想用 map[Value From File]Count
填充地图。因此,每个收到的不同数字都会有一个条目,地图中保存的值将是该值(键)被看到的次数。填充此类地图的简单方法是:
for _, v := range arr {
m[v]++
}
Playground。请注意,map
是无序的,因此您可能需要在输出结果之前对其进行排序。
注意:您可以通过 aligning the happy path to the left edge 即
来简化代码(并修复一个细微的错误)if numbers > 9 {
fmt.Println("Max Numbers = 9")
return // Important - otherwise we will still try to find duplicates in the 'large' slice
}
// Do stuff that should happen when we have 9 or fewer ints