0

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

Peter O.
  • 32,158
  • 14
  • 82
  • 96

2 Answers2

1

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));
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Ben West
  • 4,398
  • 1
  • 16
  • 16