The title sucks, but it's really very simple - given an array and a starting element, cycle between one element above, below, then two element above, and below the starting element. For example:
Start: 5
5 > 6 > 4 > 7 > 3 > 8 > 2 ...
It doesn't matter if the code initially start with the element above or below. To complicate things a little, when you reach the end or beginning of the array, the code should continue to pick valid array elements, instead of going into invalid positions:
Start: 2
2 > 3 > 1 > 4 > 0 > 5 > 6 > 7 ...
This is the code I have. It works, but I don't really like the way to fulfil the second condition above, having that two lines repeated twice.
var distance = 0;
while ((currentHeight + this.heights[index]) < height) {
sections.push(index);
currentHeight += this.heights[index];
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
if (index < 0 || index >= this.heights.length) {
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
}
}
distance is the distance from the starting point, index holds the current position. The code cycles with these two lines:
distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;
and it resolves the invalid array position problem by simply rerunning those two lines if it finds an invalid array position.