0
        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);
             }

I want to generate multiple random numbers from 0 to 6. And the total of all random numbers must be equal to 100 .. but this function is giving me a total value from 100 to 105

  • 1
    Makes sense. You need to change your code in a way that the last number will not be random but the difference of the previous sum and 100. – luk2302 Jul 02 '21 at 09:25
  • 1
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+randomly+partitioned+sum) of [Split number into 4 random numbers](/q/50405397/4642212). – Sebastian Simon Jul 02 '21 at 09:27
  • It does not really make sense that `(6 - 0)` – secan Jul 02 '21 at 09:33

2 Answers2

0

here's a working solution

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);
    }
gil
  • 2,388
  • 1
  • 21
  • 29
0

As @luk2302 mentioned, adjust the last random number push.

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);
Siva K V
  • 10,561
  • 2
  • 16
  • 29