Showing posts with label struct. Show all posts
Showing posts with label struct. Show all posts

Sunday, January 25, 2015

How to reverse an array in Ruby in O(1)

class ReverseArray < Struct.new(:array)
  include Enumerable
  def each(&blk)
    i = array.length - 1
    while i >= 0 do
      yield array[i]
      i -= 1
    end 

  end
end

array = (0..10000).to_a
reverse_array = ReverseArray.new(array)

array.last == reverse_array.first
=> true