Reputation: 13
Hopefully I make sense. I want something like this.
Consider, Total = 10
I want to divide Total into 5 parts
[n,n,n,n,n]
(If we add all numbers in this array it results to 10 )
Now suppose the increment pattern is Step = 2%
So it should be like
[n, n + 2%, n + 4%, n + 6%, n + 8%]
(adding all should result to 10)
I found this answer, but unable to add the increment pattern - Split number into 4 random numbers
Upvotes: 0
Views: 1148
Reputation: 4596
Get an array of numbers that satisfies the pattern.
var xs = [1, 1.02, 1.04, 1.06, 1.08]
Find the total of those.
var total = 0;
xs.forEach(x => total += x)
Get the ratio between that and your desired total.
var scale = 10 / total
Multiply your numbers by the scale and they will sum to 10.
var result = xs.map(x => x * scale)
Upvotes: 0
Reputation: 781068
This is a simple algebra problem to solve.
n + X%
is equivalent to n * (1 + X/100)
, so your sequence is:
n + n*1.02 + n*1.04 + n*1.06 + n*1.08 = total
// Use the distributive rule of addition over multiplication
n*(1 + 1.02 + 1.04 + 1.06 + 1.08) = total
// Simplify the sum in parentheses
n*5.20 = total
// Divide both sides by 5.20
n = total/5.20
Once you have n
you can use a for
loop to create the resulting array.
result = [];
for (let i = 0; i < 5; i++) {
result.push(n * (1 + 0.2*i));
}
Upvotes: 1