我想要做的是看看是否有一種方法可以創建一個隨機函數或使用一個內置函數,該函數能夠使用知道該程序中的哪些食物是從隨機選擇中選擇的,并且不再用于另一個星期?我目前有 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)
}
- 1 回答
- 0 關注
- 219 瀏覽
添加回答
舉報
0/150
提交
取消