亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超8個贊

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 關注
  • 219 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號