douketangyouzh5219 2017-05-17 13:50
浏览 570
已采纳

如何在Golang中随机播放数组中的字符串?

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], "
")
    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?

  • 写回答

3条回答 默认 最新

  • doufei1852 2017-05-17 14:31
    关注

    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{"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])
    

    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 <=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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮