Created
June 28, 2017 10:02
-
-
Save zarakay/41f97d763c3e30e4a940b91e2c298e20 to your computer and use it in GitHub Desktop.
Interview Question
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 | |
# the custom flatten function | |
# | |
# This function will flatten an array. | |
# | |
# param 1: the base array to add data to | |
# param 2: the array to be flattened | |
def flatten(array, items) | |
# iterate through each item in the array to be flattened | |
items.each do |item| | |
if item.kind_of?(Array) | |
# if the item is an array, recursively call the | |
# flatten fuction | |
array = flatten(array, item) | |
else | |
# if the item is not an array, just add it to the base array | |
array << item | |
end | |
end | |
# return the array | |
array | |
end | |
# the input array | |
input = [[1,2,[3]],4] | |
# call the function | |
output = flatten([], input) | |
# print out result | |
puts output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment