Created
June 6, 2016 08:51
-
-
Save Jrakesh/55de44ef292fad654b69276c0eb072ef to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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