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)
array
end
p reverse(["a", 1, "apple", 8, 90])
You can treat array as a stack and
or if you don't like modifying objects, use more functional-like
Cary mentioned in the comment about the performance. The functional approach might not be the fastest way, so if you really want to do it fast, create a buffor array and just add the items from the end to begin:
|
|||||||||
|
Recursion indeed is the solution if you're not going to use a loop.
UpdateNaturally 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:
|
|||||||||||||
|
Gentlemen, start your engines! [Edit: added two method from @Grych and results for n = 8_000.] @Grych, @ArupRakshit, @konsolebox and @JörgWMittag: please check that I've written your method(s) correctly. Methods
Benchmark
Wednesday: warm-up (n = 8_000)
Thursday: trials #1 (n = 10_000)
Friday: trials #2 (n = 50_000)
Saturday: qualifications (n = 200_000)
Sunday: final (n = 10_000_000)
|
|||||||||||||||||||||
|
One thought :-
|
|||||||||||||||||||||
|
The obvious solution is to use recursion:
We can make this tail-recursive using the standard accumulator trick:
But of course, tail recursion is isomorphic to looping. We could use a fold:
But fold is equivalent to a loop.
Really, |
|||
|
Here's another non-destructive approach:
Another would the most uninteresting method imaginable:
|
||||
|
Konsolebox is right. If they are asking for the method without loops, that simply means that you cannot use any kind of loop whether it is map, each, while, until or any even built in methods that use loops, like length, size and count etc. Everything needs to be recursive:
Ruby uses recursion to flatten, so flatten will not entail any kind of loop. |
|||
|
|
|||
|
Array#reverse
, but in the question title you are asking about reversing without using a loop (and yet you accepted an answer which uses a loop). – Jörg W Mittag Aug 3 '14 at 3:45