#174

Inverse an Array with Ruby

Ok, so this has been bothering me. And I keep forgetting to actually figure out the right solution. When I did my interview with LittleBits, I was asked to invert an array, without using a standard library reverse function. Picking Ruby to solve the problem, I immediately froze up.

Normally I'd solve the problem like so:

a = (0..10).to_a # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = a.reverse # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

If I was in something not Ruby, like Javascript, I'd do something like this:

var a =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [];
for (var i = a.length - 1; i >= 0; i--) {
    b.push(a[i]);
}

My first mistake was forgetting Ruby has for loops. I don't think I've ever actually used for in Ruby, but I discovered today that it does exist, so you can write something very similar in Ruby to the block above from Javascript.

a = (0..10).to_a
b = [];
for i in (a.size..0) do
    b += a[i];
end
p b # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

What I did instead (thinking there was no for) was this, which actually is near correct, but had one small bug:

(0..10).map {|i| k = a.index i; a[-k] } # [0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

This doesn't swap the first element. The correct solution is

(0..10).map {|i| k = a.index i; a[-(k+1)] } # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Sadly, you can't quite use this trick to do inplace substitutions:

a = (0..10).to_a
a.map! {|i| k = a.index i; a[-(k+1)] } # [10, 9, 8, 7, 6, 5, 6, 7, 8, 9, 10]

Anyways, been meaning to test that theory, just never came to mind when I was in front of an interpreter.

#ruby #interviews #javascript