dougou7782 2016-02-08 04:18
浏览 19
已采纳

想要选择一个随机数,直到所有数字都通过后才选择

I'm looking to pick a random number from 1-6 but if for example 1 is picked by the program I want to make sure it is not again used until 2-6 has been picked. I want to do this in order to have a chance to go through all options instead of having the same option 2 or maybe 3 times in a row since there are only 6 options. Any ideas please?

//choose random number for recipe
rand.Seed(time.Now().UTC().UnixNano())
myrand := random(1, 6)
fmt.Println(myrand)

...

function that processes it

//random number function
func random(min, max int) int {
    return rand.Intn(max-min) + min

}

The part of my program that uses myrand from each run is used in a if statement and is tied to the recipe that will be picked for the day

//choose random number for recipe
rand.Seed(time.Now().UTC().UnixNano())
myrand := random(1, 6)
fmt.Println(myrand)

//test below of random replacement
list := rand.Perm(6)
for i, _ := range list {
    fmt.Printf("%d
", list[i]+1)
}

//logic for recipe to choose
if myrand == 1 {
    fmt.Println(1)
    printRecipeOfTheDay(recipe1)
} else if myrand == 2 {
    fmt.Println(2)
    printRecipeOfTheDay(recipe2)
} else if myrand == 3 {
    fmt.Println(3)
    printRecipeOfTheDay(recipe3)
} else if myrand == 4 {
    fmt.Println(4)
}

}

I'm wondering if I'm doing something incorrectly ? I'm not sure how I can use the list on every run to generate a new number (myrand) and the program will be able to remember what the last number (myrand) was when it ran the previous time?

  • 写回答

1条回答 默认 最新

  • dopq87915 2016-02-08 04:23
    关注

    You can use rand.Perm(6) and then loop through the result.

    For example, here is code to print the numbers 1-6 in a random order, with no repeats:

    package main
    import "fmt"
    import "math/rand"
    
    func main(){
        list := rand.Perm(6);
        for i, _ := range list {
            fmt.Printf("%d
    ", list[i]+1);
        }
    }
    

    Note that we've added 1 to everything, since Perm(6) returns 0-5 and you want 1-6. After you've used all six, call rand.Perm(6) again for six new numbers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动