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
Recursion indeed is the solution if you're not going to use a loop. while
or until
is still a loop, and using built-in methods not doing recursion may also still be using a loop internally.
#!/usr/bin/env ruby
a = [1, 2, 3]
def reverse(array)
t = array.pop
reverse(array) if array.length > 0
array.unshift t
end
puts reverse(Array.new(a)).inspect # [3, 2, 1]
Naturally recursion has limits since it depends on the stack but that's the best you can have if you don't want to use a loop. Following Cary Swoveland's post, this is the benchmark on 8500 elements:
user system total real
@Grych 0.060000 0.010000 0.070000 ( 0.073179)
@ArupRakshit 0.000000 0.000000 0.000000 ( 0.000836)
@konsolebox 0.000000 0.000000 0.000000 ( 0.001771)
@JörgWMittag recursion 0.050000 0.000000 0.050000 ( 0.053475)
@Jörg tail 0.210000 0.040000 0.250000 ( 0.246849)
@Jörg fold 0.040000 0.010000 0.050000 ( 0.045788)
@Jörg loop 0.000000 0.000000 0.000000 ( 0.000924)
Cary rotate 0.060000 0.000000 0.060000 ( 0.059954)
Cary boring 0.000000 0.000000 0.000000 ( 0.001004)