【问题标题】:I want to generate multiple random numbers and add them but addition of all numbers must be equal to 100我想生成多个随机数并将它们相加,但所有数字的相加必须等于 100
【发布时间】:2021-07-02 09:24:22
【问题描述】:
        let totalMoves = 0;
        let carMoves = [];
        while (totalMoves <= 100) {
            let random = Math.floor(Math.random() * (6 - 0) + 1);
                totalMoves = totalMoves + random;
                carMoves.push(random);
            console.log("Total Moves" + totalMoves);
             }

我想生成从 0 到 6 的多个随机数。所有随机数的总和必须等于 100 .. 但是这个函数给我一个从 100 到 105 的总值

【问题讨论】:

标签: javascript arrays ecmascript-6 logic


【解决方案1】:

这是一个可行的解决方案

let totalMoves = 0;
    let carMoves = [];
    while (totalMoves < 100) {
        let validRandomRange = Math.min(6, 100-totalMoves)
        let random = Math.floor(Math.random() * (validRandomRange) + 1);
        totalMoves = totalMoves + random;
        carMoves.push(random);
        console.log("Total Moves" + totalMoves);
    }

【讨论】:

    【解决方案2】:

    如@luk2302所说,调整最后的随机数推送。

    let totalMoves = 0;
    const carMoves = [];
    const size = 6;
    while (totalMoves <= 100 - size) {
      let random = Math.floor(Math.random() * (size + 1));
      totalMoves = totalMoves + random;
      carMoves.push(random);
      if (totalMoves >= 100 - size) {
        carMoves.push(100 - totalMoves);
      }
    }
    console.log("Total Moves ", totalMoves);
    console.log("car Moves  ", carMoves);

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      相关资源
      最近更新 更多