I want to get multiple random elements from list in same time, but need to be real random not every time same elements.
Second problem is : i want to get uniq element from the list, example if i get 08, this code need to be removed from list and get net random exclude 08 string.
this is my actual code :
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Won't work on the Playground since the time is frozen.
rand.Seed(time.Now().Unix())
reasons := []string{
"01","02","03","04", "05", "06", "07", "08", "09", "10",
}
n := rand.Int() % len(reasons)
n1 := rand.Int() % len(reasons)
n2 := rand.Int() % len(reasons)
fmt.Println("", reasons[n])
fmt.Println("", reasons[n1])
fmt.Println("", reasons[n2])
}
my output is this :
07
02
06
every time return me same output, i want to be random and unique
To get a unique answer all you have to do is remove the existing answer from the slice. I have knocked something together which does that using a function. There are more efficient ways to do it, but this is simple to see what is happening.
func main() {
rand.Seed(time.Now().Unix())
reasons := []string{
"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
}
n, reasons := getRandom(reasons)
n1, reasons := getRandom(reasons)
n2, reasons := getRandom(reasons)
fmt.Println("", n)
fmt.Println("", n1)
fmt.Println("", n2)
}
func getRandom(reasons []string) (string, []string) {
n := rand.Int() % len(reasons)
switch n {
case 0:
return reasons[0], reasons[1:]
case len(reasons) - 1:
return reasons[n], reasons[:n]
}
newSlice := []string{}
for i, item := range reasons {
if i != n {
newSlice = append(newSlice, item)
}
}
return reasons[n], newSlice
}