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

如何使用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条回答 默认 最新

  • duanpo1821 2013-11-21 04:28
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低