Home > database >  How to create a map and find duplicates in go
How to create a map and find duplicates in go

Time:03-17

I'm new to go and can't figure out how to do this task:

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

I have completed this task halfway, but I can't figure out how to do duplicate tracking via map

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 {
        
        
    }

CodePudding user response:

It looks like you are tying to populate the map with map[Value From File]Count. So there will be an entry for each distinct number received and the value held in the map will be the number of times the value (key) has been seen. A simple way to populate such a map is:

for _, v := range arr {
        m[v]  
}

Playground. Note that a map is unordered so you may need to sort the results before you output them.

Note: You can simplify you code (and fix a subtle bug) by aligning the happy path to the left edge i.e.

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
  • Related