为了账号安全,请及时绑定邮箱和手机立即绑定

Golang程序中的随机函数和持久化

Golang程序中的随机函数和持久化

Go
开满天机 2021-12-07 19:41:51
我想要做的是看看是否有一种方法可以创建一个随机函数或使用一个内置函数,该函数能够使用知道该程序中的哪些食物是从随机选择中选择的,并且不再用于另一个星期?我目前有 1-6 种食物,但我想确保一周内不会连续两次选择相同的食物,例如 2。此外,我希望程序能够写下最后选择的项目,这样它至少一周内不会再次选择它。我能用一个可以读取的简单文本文件来完成这个吗?package mainimport (    "fmt"    "math/rand"    "time")type Recipe struct { //Struct for recipe information    name        string    prepTime    int    cookTime    int    Ingredients []string //this is now a slice that will accept multiple elements    ID          int    Yield       int}func main() {    var recipe1 Recipe //Declare recipe1 of Type Recipe    var recipe2 Recipe    var recipe3 Recipe    /* recipe1 specifications */    recipe1.name = "BBQ Pulled Chicken"    recipe1.prepTime = 25    recipe1.cookTime = 5    recipe1.Ingredients = append(        recipe1.Ingredients,        "1 8-ounce can reduced-sodium tomato sauce",    )    recipe1.Ingredients = append(        recipe1.Ingredients,        "1/2 medium onion (grated),",    )    recipe1.ID = 1    recipe1.Yield = 8    /* Recipe 2 specifications */    recipe2.name = "Steak Tacos with Pineapple"    recipe2.prepTime = 45    recipe2.cookTime = 45    recipe2.Ingredients = append(        recipe2.Ingredients,        "3 tablespoons soy sauce,",    )    recipe2.Ingredients = append(        recipe2.Ingredients,        "1 tablespoon finely grated garlic,",    )    recipe2.Ingredients = append(        recipe2.Ingredients,        "1 tablespoon finely grated peeled fresh ginger,",    )    recipe2.Ingredients = append(        recipe2.Ingredients,        "1 1/2 pounds skirt steak, cut into 5-inch lengths,",    )    recipe2.Ingredients = append(        recipe2.Ingredients,        "Salt",    )    recipe2.Ingredients = append(        recipe2.Ingredients,        "Pepper",    )
查看完整描述

1 回答

?
弑天下

TA贡献1818条经验 获得超7个赞

Perm 可能是您想要使用的。这是一个将为您生成伪随机列表的示例。您可以将其保存到 json 编码的文件中。然后,如果您有 7 个食谱,您可以使用 time.Weekday 从切片中获取食谱编号,使用星期几作为切片的关键。一旦您达到某个预定日期,只需重新生成切片并保存。


package main


import "fmt"

import "math/rand"

import "time"


func main() {


  r := rand.New(rand.NewSource(time.Now().UnixNano()))

  i := r.Perm(6)

  fmt.Printf("%v\n", i)

}


查看完整回答
反对 回复 2021-12-07
  • 1 回答
  • 0 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信