Skip to content

Instantly share code, notes, and snippets.

@aashish
Last active September 10, 2017 19:38
Show Gist options
  • Save aashish/52473eee52500960241d57d659f845aa to your computer and use it in GitHub Desktop.
Save aashish/52473eee52500960241d57d659f845aa to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers in ruby
#!/usr/bin/env ruby
class Array
def flatter
if empty? # base case
self
else
tail = pop
if tail.kind_of? Array
flatter + tail.flatter
else
flatter << tail
end
end
end
end
puts "Specs"
puts "====="
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]],
[[[1], 2], 3]
]
cases.each_with_index do |c, i|
print "#{i}. "; print c; puts
d = c.dup
a = d.flatten
r = c.flatter
print "flatter result: "; print r; puts
print "flatten resul: "; 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