1

I already find a solution on this community but I can't find a solution. My question is "How to random a decimal number from maximum in JavaScript?"

Example: If I set Total to 1 and Size to 5, Then I want to generate a decimal number to an array(Size 5) that Sum total at 1.

Sum Total: 1
Array Size: 5

Result Array:

[0.23, 0.12, 0.4, 0.14, 0.11]

Thank you for all advice. Best regards.

  • 1
    What have you tried so far? – MTCoster Dec 09 '18 at 16:27
  • @MTCoster My client want to have this function, But I never do like this before. – Wongsakorn Suksiri Dec 09 '18 at 16:31
  • If you want help with a solution, you have to show us you’ve made an effort. The easiest way to do that is to show us what you’ve tried to make it work. – MTCoster Dec 09 '18 at 16:33
  • @MTCoster Now my client have to key it manually. But my customer want an automatic function that can do for them. I think if I know the solution I can do it by myself but now I don't know any logic of this function that can generate it automatically. I already have a result only. – Wongsakorn Suksiri Dec 09 '18 at 16:39
  • "*I already find […] but I can't find […].*" - Huh? – Bergi Dec 09 '18 at 16:56
  • @WongsakornSuksiri Do you know how to generate an array of 5 numbers? If yes, that's the code you should start with. Please [edit] your question to show it - even if it doesn't completely work yet. – Bergi Dec 09 '18 at 16:57

1 Answers1

0

If I understand your requirements correctly, you want to generate an array of n numbers with a fixed sum (let’s call it s).

Let’s start by generating n random numbers. Javascript’s Math.random() creates numbers between 0 and 1, like this:

function randomArray(length, sum) {
  return new Array(length).fill(0).map(() => Math.random());
}

const rand = randomArray(5, 1);
console.log(rand);

console.log('Sum: ', rand.reduce((a, b) => (a + b), 0));

This function creates a new array using the length parameter, fills it with 0 to initialize it, then replaces every element with a random number.

To meet the sum restriction, we need to do three things:

  • Sum all the random numbers;
  • Divide the desired sum by the calculated sum to acquire a scale factor, and
  • Multiply every number by this scale factor.

function randomArray(length, sum) {
  const rawRandom = new Array(length).fill(0).map(() => Math.random());
  const multiplier = sum / rawRandom.reduce((a, b) => (a + b), 0);
  return rawRandom.map(n => (n * multiplier));
}

const rand = randomArray(5, 1);
console.log(rand);

console.log('Sum: ', rand.reduce((a, b) => (a + b), 0));
MTCoster
  • 5,868
  • 3
  • 28
  • 49