Search code examples
arraysalgorithmgouniqueslice

How to get some unique random items from a slice


In this code

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    rand.Seed(86)
    items := []string{"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"}
    item1 := items[rand.Intn(len(items))]
    item2 := items[rand.Intn(len(items))]
    item3 := items[rand.Intn(len(items))]
    fmt.Print(item1 + " ")
    fmt.Print(item2 + " ")
    fmt.Print(item3)
    fmt.Println()
}

playground

I want to get three different items from list items. But this method will return same data sometimes as everytime is random like

bbb ddd ddd

How to get unique data and loop all the patterns?

Such as

aaa bbb ccc
aaa bbb ddd
aaa bbb eee
aaa bbb fff
aaa bbb ggg
bbb ccc ddd
bbb ccc eee
bbb ccc fff
bbb ccc ggg
ccc ddd eee
ccc ddd fff
ccc ddd ggg
ddd eee fff
ddd eee ggg
eee fff ggg

Solution

Use this code can get all the permutations, but some of them returned same data, just changed index.


Solution

  • Don't use static value on rand package seeds and first you need to read this :

    Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Seed values that have the same remainder when divided by 2³¹-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

    So seeds are static value when you provide init value.

    You need to do something like this :

    rand.Seed(time.Now().UnixNano())