Skip to content

Instantly share code, notes, and snippets.

@hannelita
Created March 24, 2017 17:04
Show Gist options
  • Save hannelita/19cc5b82f410ebc4bc641d7e1d538be9 to your computer and use it in GitHub Desktop.
Save hannelita/19cc5b82f410ebc4bc641d7e1d538be9 to your computer and use it in GitHub Desktop.
#Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4]
# -> [1,2,3,4].
# input = [[1,2,[3]],4]
# input = [[1]]
input = [[[1]], [2,3,4], [[[[6, 7]]]]]
class Flatter
#works for any generic element. Recursive calls
def self.flat(input_arr, output_flat)
input_arr.each do |element|
if element.is_a? Array
(self.flat(element, output_flat))
else
(output_flat.push(element))
end
end
return output_flat
end
end
unless input.is_a? Array
raise "Please provide me an Array (or nested array)"
else
response = Flatter.flat(input, [])
print response
end
class FlatterStr
#no recursion, less safety about types - elements need to be an integer
def self.flat(input_arr)
input_str = input_arr.to_s
output_flat = []
input_str.split("").each do |char|
if (/\A[-+]?\d+\z/ === char)
output_flat.push(char.to_i)
end
end
return output_flat
end
end
unless input.is_a? Array
raise "Please provide me an Array (or nested array)"
else
response = FlatterStr.flat(input)
print response
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment