如何在切片中删除重复的元素?

huangapple go评论79阅读模式
英文:

How to remove repeated element in a slice?

问题

我已经编写了一段代码来生成随机数并删除重复的数字,代码如下:

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 !contains(list, s) {
			list[i] = s
		} else {
			goto here
		}
	}
	fmt.Println("list:", list)
}

func contains(list [7]int, num int) bool {
	for _, value := range list {
		if value == num {
			return true
		}
	}
	return false
}

我注意到代码中有很多重复的部分,例如:

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

但是当我将其改为:

s!=list[0:6]

时,代码是错误的。你应该如何正确地实现这个功能呢?

英文:

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

package main

import (
	&quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;time&quot;
)

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

	}
	fmt.Println(&quot;list:&quot;, list)
}

I noticed that there were a lot repeated code like:

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

But when I write it to:

s!=list[0:6]

It is wrong, how can I do this properly?

答案1

得分: 12

将其存储在映射中。

像这样:

rndmap := make(map[int]bool)

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

结果映射将不会存储重复的索引。

您可以像这样将其转换为切片:

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

Store it in map.

like that

rndmap := make(map[int]bool)

for len(rndmap) &lt; 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

得分: 2

你可以使用标准库来生成首次没有重复的随机元素。

package main

import (
	"fmt"
	"math/rand"
)

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

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

package main

import (
	&quot;fmt&quot;
	&quot;math/rand&quot;
)

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

答案3

得分: 1

如果你想要检查一个整数切片中是否存在某个值,可以尝试使用以下函数:

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

你可以像下面这样使用它,但是在play.golang.org上无法成功运行,因为play.golang.org对math/rand有确定性的响应(在我的情况下,它是0),这将阻止它给出多个答案,将代码强制进入无限循环。

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
        }
    }
}
英文:

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 &lt; 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
    }

}

答案4

得分: 0

以下程序将选择在函数findDuplicates()中传递的数组,并将重复的值作为输出放入另一个数组中。如果没有重复值,函数将返回-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}))
}

// 输出 [22 1 1 22]

请注意,这是一个用Go语言编写的程序,用于查找数组中的重复值并返回。

英文:

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 &quot;fmt&quot;

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

	for i := 0; i &lt; 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]

huangapple
  • 本文由 发表于 2013年11月21日 10:14:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/20111170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定