Ruby Arrays: Cloning and Rotating
Whilst working on problem 68 of Project Euler, I have encountered 2 interesting issues. The first one was cloning a multi-dimensional array, and the second one rotating an array.
Here is the problem I met with cloning:
a = [[0,0],[0,0]]
b = a.clone
b[0][0] = 1 # Update b array
puts a # print a
And this prints out:
1,0,0,0
What?! Did I not clone array a
, then? Well, I had forgotten that the clone
method doesn’t do a deep copy, and therefore the arrays within the array are still references. Therefore, à la Java, if I update an array, I end up updating the other one. So I had to create my own array_copy
function:
def array_copy v
a = []
v.each{ |e| a << e.clone }
a
end
Now, the rotation of the array was more trivial after finding this...
num.times{ a << a.shift }
Neat! :)
I used a backtracking algorithm to solve this problem 68, and I’m pretty satisfied with it, but I think it can do with a bit of clean up… This brings me to 71 solved!