簡體   English   中英

使用“.push”從 arrays 生成 arrays 時,如何更好地“隨機化”我的結果並控制重復項?

[英]When generating arrays from arrays using “.push”, how can I better “randomize” my results and control for duplicates?

我正在研究這個練習題來學習 JavaScript。 我希望以后能夠在 Python 和 Java 中做同樣的事情。 但是現在,我正在嘗試創建一個包含 30 種獨特午餐的列表。

Tanya 是學校系統食堂的經理。 每個月她都需要想出下個月的學校午餐。 學校午餐應該有各種不同的主菜、配菜和甜點。

為 Tanya 編寫一個程序,為她整理午餐。
列出主菜、配菜和甜點的清單 能夠生成膳食清單。 飯菜應該是獨一無二的。

我正在嘗試生成 30 種 arrays 組合,其中包括“主菜”、“配菜”和“甜點”,但沒有重復條目。

我有 5 個主菜、5 個配菜和 5 個甜點,我寫的代碼吐出了 125 種不同的食物,盡管有很多重復。 我想要的是能夠更好地將其組織成 30 天的塊,例如 11 月、12 月等。我想編寫一個程序,允許虛構的客戶輸入新的主菜、配菜或甜點,但我想需要一些前端 HTML 和 Jquery 嗎?

const MEAL_COUNT = 30;

const mains=["Chicken sandwich ", "Lasagna ", "Pizza ", "Fried Beefcake ", "Soylent Shake "];
const sides=["Fries ", "Apple slices ", "Tater Tots ", "Sad Salad ", "Hard-boiled egg "];
const desserts=["Rice Pudding ", "Gluten-free cookie ", "Cheesecake Delux ", "Sundae ", "Graham Crackers "];

const meals = [];

const mealIdentifiers = [];

while (meals.length < MEAL_COUNT) {

    let mainId = Math.floor(Math.random() * mains.length);
    let sideId = Math.floor(Math.random() * sides.length);
    let dessertId= Math.floor(Math.random() * desserts.length);

    let mealId = `${mainId}${sideId}${dessertId}`;

if (mealId.includes(id)) {
        continue;
}

meals.push({
    main: mains[mainId],
    side: sides[sideId],
    dessert: desserts[dessertId]
  });
}

console.log(meals);

編輯:我通過刪除if (mealId.includes())中的“id”來使這段代碼工作

UPDATE2:我已經在 HTML 中以漂亮的方式顯示了這個! 只是想分享! JSFiddle

與其迭代每個數組,不如迭代“直到你有 30 頓飯”,使用Math.random()在每次迭代時從你的主菜、配菜和甜點中獲取元素,然后檢查“我之前是否已經創建過這個組合?” . 如果你這樣做了,忽略它並重試,如果你沒有,將它添加到你的膳食列表中:

const MEAL_COUNT = 30;

const mains = [...];
const sides = [...];
const desserts = [...];

// we start with an empty meal list.
const meals = [];

// and meal compositions are unique, so we need a way to track them.
const mealIdentifiers = [];

// start inventing meals!
while (meals.length < MEAL_COUNT) {

  // Get three random element ids, rounded down
  let mainId = Math.floor(Math.random() * mains.length);
  let sideId = Math.floor(Math.random() * mains.length);
  let puddId = Math.floor(Math.random() * mains.length);

  // form the unique identifier for this meal. In this case
  // we simply string-combine the ids, but that WON'T WORK
  // for lists that are more than 9 elements long (and you
  // should be able to explain why).
  let mealId = `${mainId}${sideId}${puddId}`;

  // have we seen this unique meal already?
  if (mealIdentifiers.includes(mealId)) {
    // we have. Continue to the next iteration.
    continue;
  }

  // if we get here, we haven't, so add it to the list.

  meals.push({
    main: mains[mainId],
    side: sides[sideId],
    dessert: desserts[puddId]
  });

  mealIdentifiers.push(mealId);
}

您的meals點數組現在包含 30 個餐點,每個餐點都是方便的 object 和.main.side.dessert屬性,您可以在任何代碼中引用這些屬性,以便將這些信息實際呈現給用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM