How to shuffle strings in arrays in golang?
因此,我创建了一个程序来帮助我确定要玩哪个游戏。在开始问题之前,让我向您展示我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package main import ( "fmt" "strconv" "time" ) func main() { isArray := [10]string{"Paladins","Overwatch","CS:GO","Tanki","Left 4 Dead","Rocket League","Call Of Duty : AW","Portal","Star Citizen","Star Wars : Battlefront"} fmt.Print("0,1,2,3,4,5,6,7,8,9 :=") var ( va string ar string ) fmt.Scanln(&va) i, _ := strconv.Atoi(va) fmt.Print("You Should Play :") fmt.Print(isArray[i],"\ ") fmt.Print("[Y/N] :=") fmt.Scanln(&ar) if ar !="N" || ar !="n" { fmt.Print("OK") } time.Sleep(3 * time.Second) } |
因此,如果我已经两次知道使用哪个号码触发游戏,那么问题就会开始。因此,我试图使字符串随机化,就像每次使用时都随机播放一样,该怎么做呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package main import ( "fmt" "math/rand" "time" ) func shuffle(src []string) []string { final := make([]string, len(src)) rand.Seed(time.Now().UTC().UnixNano()) perm := rand.Perm(len(src)) for i, v := range perm { final[v] = src[i] } return final } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package main import ( "fmt" "math/rand" "time" ) type list []string func main() { s := list{ "Tanki", "Left 4 Dead", "Rocket League", "Call Of Duty : AW", } s.shuffle() s.print() } func (l list) print() { for i, v := range l { fmt.Println(i, v) } } func (l list) shuffle() list { src := rand.NewSource(time.Now().UnixNano()) r := rand.New(src) for i := range l { n := r.Intn(len(l) - 1) l[i], l[n] = l[n], l[i] } return l } |
那么,就您的问题而言,为什么不使用
1 2 3 4 | isArray := [10]string{"Paladins","Overwatch","CS:GO","Tanki","Left 4 Dead","Rocket League","Call Of Duty : AW","Portal","Star Citizen","Star Wars : Battlefront"} n := rand.Intn(9) fmt.Printf("You Should Play : %s\ ", isArray[n]) |
但是,如果您想为此对数组中的字符串进行混洗,则可以像这样进行处理:
1 2 3 4 5 6 7 8 9 | // Shuffle array in place l := len(isArray)-1 for i := 0; i <=l; i++ { n := rand.Intn(l) // swap x := isArray[i] isArray[i] = isArray[n] isArray[n] = x } |
这应该是O(n),尽管我不确定