Skip to content

Instantly share code, notes, and snippets.

@Jrakesh
Created June 6, 2016 08:51
Show Gist options
  • Save Jrakesh/55de44ef292fad654b69276c0eb072ef to your computer and use it in GitHub Desktop.
Save Jrakesh/55de44ef292fad654b69276c0eb072ef to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def rakesh_flatten(input, level = -1)
result = []
def result.recursive(input, level)
input.each do |ele|
if Array === ele && level != 0
recursive(ele, level - 1)
else
self << ele
end
end
end
result.recursive(input, level)
result
end
inputs = [
[],
[1],
[1, 2, 3],
[1, [2, 3]],
[1,2,[3,4],5,[6,[7,8]],[9]]
]
inputs.each_with_index do |orig_array, i|
print "#{i + 1}) "; print orig_array; puts
dup_array = orig_array.dup
flat_dup_array = dup_array.flatten
flat_orig_array = rakesh_flatten(orig_array)
print "Flattened original array: "; print flat_orig_array; puts
print "Flattened duplicate array: "; print flat_dup_array; puts
puts (flat_orig_array == flat_dup_array) ? "PASS" : "FAIL"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment