Created
September 9, 2010 05:04
-
-
Save ma11hew28/571402 to your computer and use it in GitHub Desktop.
Ruby implementation of flatten for nested arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Array | |
def mattflat | |
if empty? # base case | |
self | |
else | |
tail = pop | |
if tail.kind_of? Array | |
mattflat + tail.mattflat | |
else | |
mattflat << tail | |
end | |
end | |
end | |
end | |
class FunArray < Array | |
def play | |
puts "have fun!" | |
end | |
end | |
puts "Specs" | |
puts "=====" | |
f = FunArray.new(2) | |
f[0] = 1 | |
f[1] = FunArray.new(2) | |
f[1][0] = 2 | |
f[1][1] = 3 | |
cases = [ | |
[], | |
[1], | |
[1, 2, 3], | |
[1, [2, 3]], | |
[1, [2, [3, 4]]], | |
[1, [2, [3, 4], [5, 6, [7, 8, [9, 10, 11], [12]]]], 13, [14, 15], [16]], | |
f | |
] | |
cases.each_with_index do |c, i| | |
print "#{i}. "; print c; puts | |
d = c.dup | |
a = d.flatten | |
r = c.mattflat | |
print "r: "; print r; puts | |
print "a: "; print a; puts | |
puts (r == a) ? "pass" : "fail" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment