kimimaro
kimimaro

Reputation: 1263

Looping through an array with changed step based on last loop's result

I have learned about this answer, and know we can do this:

(0..array.length - 1).step(2).each do |index|
    value_you_care_about = array[index]
end

However I found that syntax cannot go for a step which changed self by result of last loop. Like C++ code as follow:

for(int x = 1; x<cx; x+=x){
    value_i_care_about = array[x];
    //do something with the value I care about.  
}

This is not same to that question, since x plus itself as a loop step. Does anyone know how to code this? This is useful such as in a merge-sort implementation.

Very appricate for any help!


Update:

As far as I know is we only can implement by following code:

step = 1
while step < nums.length do
    // do sth.
    step += step
end

Is there a better implementation?

Upvotes: 0

Views: 55

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

If you hate phpish declarations in front of the loop (step = 1), as I do, you might find the approach with infinite loop useful:

loop.inject(1) do |x| 
  break if x > 10
  puts x
  x += x
end
#⇒ 1
#  2
#  4
#  8

Upvotes: 1

Related Questions