简体   繁体   中英

How to remove repeated element in a slice?

I have made a code to generate random numbers and delete the repeated ones like below:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    list := [7]int{}
    for i := 0; i < 7; i++ {
    here:
        rand.Seed(time.Now().UnixNano())
        s := rand.Intn(16)
        fmt.Println(s)
        if s != list[0] && s != list[1] && s != list[2] && s != list[3] && s != list[4] && s != list[5] && s != list[6] {
            list[i] = s
        } else {
            goto here
        }

    }
    fmt.Println("list:", list)
}

I noticed that there were a lot repeated code like:

s!=list[0]&&list[1]

But when I write it to:

s!=list[0:6]

It is wrong, how can I do this properly?

Store it in map.

like that

rndmap := make(map[int]bool)

for len(rndmap) < YOUR_LEN {
    rndmap[rand.Intn(YOUR_MAX_RAND)] = true
}

Result map will never store repeated indexes.

You can convert it into slice like this

rndslice := make([]int,0)
for i, _ := range rndmap {
    rndslice = append(rndslice, i)
}

You can use the standard library to generate the random elements without any repetition in the first place.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println(rand.Perm(16)[:7])
}

If you want a way to check a slice of ints for a value, try this function ( play.golang.org ):

func InSlice (arr []int, val int) (bool){
    for _, v := range(arr) {
         if v == val { return true; } 
    }    
    return false; 
}

You can use this like below, but you won't be able to run it succesfully on play.golang.org because play.golang.org has a deterministic response to math/rand (In my case, it's 0), which will keep it from giving more than one answer, forcing this code into an infinite loop.

func main() {
    list := [7]int{}
    for i := 0; i < 7; i++ {
    here:
        rand.Seed(time.Now().UnixNano())
        s := rand.Intn(16)
        fmt.Println(s)
        if !InSlice(list[:], s) {
            list[i] = s
        } else {
            goto here
    }

}

The following program will pick the array passed in the function findDuplicates() and returns repeated / duplicate values in another array as output. Also if there are no duplicates the function will return -1.

package main

import "fmt"

func findDuplicates(arr []int) []int {
    foundMap := make(map[int]bool, 0)
    respArray := []int{}

    for i := 0; i < len(arr); i++ {
        if foundMap[arr[i]] == true {
            respArray = append(respArray, arr[i])
        } else {
            foundMap[arr[i]] = true
        }
    }
    if len(respArray) == 0 {
        respArray = append(respArray, -1)
    }

    return respArray
}

func main() {
    fmt.Println(findDuplicates([]int{19, 22, 22, 100, 1, 1, 1, 22, 88}))
}

// Output [22 1 1 22]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM