Ashbury
Ashbury

Reputation: 2346

Every n times, skip n items and increase n by 1

This is probably an odd question since I have a solution (below), but was hoping someone could show me a more succinct or readable way to do this:

I created a loop that outputs the following array:

[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91]

the gaps between numbers get progressively larger:

etc.

I did it by creating two variables, step keeps track of the gap size and count keeps track of the current 'position' in the gap. count counts down to zero, then increases step by one.

var output = [];
var step = 0;
var count = 0;

for (var i = 0; i < 100; i++) {
  if (count == 0){
    step += 1;
    count = step;
    output.push(i);
  }
  count -= 1;
}

Upvotes: 0

Views: 149

Answers (3)

kwarnke
kwarnke

Reputation: 1514

You can save the total helper variable with this solution:

var output = [0]

for (var i = 1; i < 14; i++) {
  output.push(output[i - 1] + i)
}

console.log(output) // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]

This solution takes into account that the value to add the counter value to is already present at the last position in the array.

A recursive version is also possible:

output = (function f(x) {
  return x.length == 14 ? x : f(x.concat([x[x.length - 1] + x.length]))
})([0])

console.log(output); // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]

Here is no additional counter variable is needed. I use concat because it returns an array what I need for the recursive call, where push returns the new array length. The argument for concat is an array with one element with the new value to add.

Try online

Upvotes: 0

Oriol
Oriol

Reputation: 288250

You should skip useless iterations. If you want a sequence of 100 numbers, use

var output = [];
var step = 0;
for (var i = 0; i < 100; i++) {
  step += i;
  output.push(step);
}

If you want the general term,

aₙ = ∑ⁿᵢ₌₀ i = n*(n+1)/2

So you can also do

var output = [];
for (var i = 0; i < 100; i++) {
  output.push(i * (i+1) / 2);
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521409

You can try the following:

var output = [];
var total = 0;

for (var i=1; i < 100; i++) {
    output.push(total);
    total += i;
}

The gaps between numbers simply increase by one for each step, so a for loop should be able to track this change.

Upvotes: 2

Related Questions