douaoj0994
2013-11-21 02:14
浏览 799
已采纳

如何使用golang检查数组中的重复元素?

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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题