Where can I find or how can I make a number generator from a number? For example, I have the number 66, I need to scatter it into X parts, so that adding all these parts will result in the same number.
2 answers
In short, the code is easier to write than in words :)
var out = [], X= 8, Y = 111111; for (var i = X-1; i > 0; i--) { var p = Math.floor(Math.random() * (Y - i))+1; Y -= p; out.push(p); } out.push(Y); console.log(out);
http://jsfiddle.net/oceog/rgHL6/
This is if there are no other restrictions.
- but where are the doubts? - DreamChild
- onejvas! = javascript you probably still don’t understand much. - zb '
|
Here is another idea for a more even distribution (sorry, just an idea):
- Let
X
be the number of numbers,Y
desired amount. - We generate
X
random numbers from 0 to 1. - We summarize them, let
S
be their sum. - Put
K = Y / S
, multiply all random numbers by K - If you need integers , round off, and if you need to adjust the amount, modify the last term.
|
X - 1
units of units, and one piece66 - Х + 1
. Or generallyX - 1
pieces of zeros, and one piece66
. - VladD