如何在Golang中对数组中的字符串进行洗牌?

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

How to shuffle strings in arrays in golang?

问题

所以我创建了一个程序来帮助我决定玩哪个游戏。在我开始解释我的问题之前,让我先展示给你我的代码:

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], "\n")
	fmt.Print("[Y/N] := ")
	fmt.Scanln(&ar)

	if ar != "N" || ar != "n" {
		fmt.Print("OK")
	}

	time.Sleep(3 * time.Second)
}

问题出现在当我已经知道哪个数字会触发一个游戏时,如果我使用它两次。所以我正在尝试使字符串随机化,每次使用时都进行洗牌,我该如何做到这一点?

英文:

So I created a program to help me decide which game to play. Before I start my problem let me show you my code:

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], "\n")
	fmt.Print("[Y/N] := ")
	fmt.Scanln(&ar)

	if ar != "N" || ar != "n" {
		fmt.Print("OK")
	}

	time.Sleep(3 * time.Second)
}

So the problems start when I already know which number would trigger a game, if I use it twice. So I am trying to make the strings random, like shuffling each time I use it, how can I do that?

答案1

得分: 2

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
}
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
}

这段代码是一个用于打乱字符串切片顺序的函数。它使用了随机数生成器来生成一个随机的排列,并将原始切片按照这个排列重新排序后返回。

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

答案2

得分: 0

好的,以下是翻译好的内容:

嗯,对于你的问题,为什么不使用rand.Intn()来选择一个随机数并打印游戏,而不是让用户选择一个数字呢?

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("你应该玩:%s\n", isArray[n])

但是,如果你只是为了打乱数组中的字符串,你可以像这样原地进行操作:

// 原地打乱数组
l := len(isArray)-1
for i := 0; i <= l; i++ {
    n := rand.Intn(l)
    // 交换
    x := isArray[i]
    isArray[i] = isArray[n]
    isArray[n] = x
}

这应该是O(n)的时间复杂度,尽管我不确定Intn的复杂度。如果你真的想要更高级一点,你可以:

  1. 创建一个第二个数组(randomArray),其中包含一个随机数和isArray中元素的位置。
  2. 按照随机数对这个数组进行排序。
  3. 创建一个新数组,按照randomArray的顺序复制isArray中的元素。
英文:

Well, literally for your problem why not use rand.Intn() to choose a random number and print the game rather than make the user pick a number?

isArray := [10]string{&quot;Paladins&quot;, &quot;Overwatch&quot;, &quot;CS:GO&quot;, &quot;Tanki&quot;, &quot;Left 4 Dead&quot;, &quot;Rocket League&quot;, &quot;Call Of Duty : AW&quot;, &quot;Portal&quot;, &quot;Star Citizen&quot;, &quot;Star Wars : Battlefront&quot;}
n := rand.Intn(9)
fmt.Printf(&quot;You Should Play : %s\n&quot;, isArray[n])

But if you want to shuffle strings in an array for the sake of it, then you can do it in place like this:

// Shuffle array in place
l := len(isArray)-1
for i := 0; i &lt;=l; i++ {
    n := rand.Intn(l)
    // swap
    x := isArray[i]
    isArray[i] = isArray[n]
    isArray[n] = x
}

This should be O(n), though I'm not sure about the complexity of Intn. If you really want to be fancy, you could:

  1. Create a second array (randomArray) of touples, containing a random number and element position in isArray.
  2. Sort this array by the random number
  3. Create a new array, copying elements of isArray, but ordered by our randomArray

答案3

得分: 0

包 main

import (
"fmt"
"math/rand"
"time"
)

type list []string

func main() {

s := list{
    "坦克大战",
    "生化危机",
    "火箭联盟",
    "使命召唤:高级战争",
}
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
}

英文:
package main

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

type list []string

func main() {

	s := list{
    	&quot;Tanki&quot;,
	    &quot;Left 4 Dead&quot;,
	    &quot;Rocket League&quot;,
	    &quot;Call Of Duty : AW&quot;,
	}
    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
}

答案4

得分: 0

你现在可以使用math包中的rand.Shuffle函数。

	var games = [10]string{"Paladins", "Overwatch", "CS:GO", "Tanki", "Left 4 Dead", "Rocket League", "Call Of Duty : AW", "Portal", "Star Citizen", "Star Wars : Battlefront"}

	rand.Seed(time.Now().UnixNano())
	rand.Shuffle(len(games), func(i, j int) {
		games[i], games[j] = games[j], games[i]
	})

	fmt.Println(games)

文档:https://pkg.go.dev/math/rand#Shuffle

英文:

You can now use the rand.Shuffle function from the math package.

	var games = [10]string{&quot;Paladins&quot;, &quot;Overwatch&quot;, &quot;CS:GO&quot;, &quot;Tanki&quot;, &quot;Left 4 Dead&quot;, &quot;Rocket League&quot;, &quot;Call Of Duty : AW&quot;, &quot;Portal&quot;, &quot;Star Citizen&quot;, &quot;Star Wars : Battlefront&quot;}

	rand.Seed(time.Now().UnixNano())
	rand.Shuffle(len(games), func(i, j int) {
		games[i], games[j] = games[j], games[i]
	})

	fmt.Println(games)

docs: https://pkg.go.dev/math/rand#Shuffle

huangapple
  • 本文由 发表于 2017年5月17日 21:50:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/44026823.html
匿名

发表评论

匿名网友

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

确定