Reverse an array without using a loop in ruby

后端 未结 8 455
时光说笑
时光说笑 2021-01-24 12:12

I have a coding challenge to reverse a an array with 5 elements in it. How would I do this without using the reverse method?

Code:

def reverse(array)
 a         


        
8条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 13:01

    The obvious solution is to use recursion:

    def reverse(array)
      return array if array.size < 2
      reverse(array.drop(1)) + array.first(1)
    end
    

    We can make this tail-recursive using the standard accumulator trick:

    def reverse(array, accum=[])
      return accum if array.empty?
      reverse(array.drop(1), array.first(1) + accum)
    end
    

    But of course, tail recursion is isomorphic to looping.

    We could use a fold:

    def reverse(array)
      array.reduce([]) {|accum, el| [el] + accum }
    end
    

    But fold is equivalent to a loop.

    def reverse(array)
      array.each_with_object([]) {|el, accum| accum.unshift(el) }
    end
    

    Really, each_with_object is an iterator and it is the side-effectful cousin of fold, so there's actually two reasons why this is equivalent to a loop.

提交回复
热议问题