Created
July 25, 2018 13:20
-
-
Save Maghraby/494d574ee5a83362af89da7b84fa1f58 to your computer and use it in GitHub Desktop.
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
class Array | |
## Here i want to flatten an array | |
## by a given number of dimensions if an argument is passed | |
def my_flatten(n = nil) | |
n ? multiple_flatten(self, n) : recursive_flatten(self) | |
end | |
private | |
## flattening an array by one diemention | |
## Example: | |
## array = [1, [2, 3, [4, 5]]] | |
## single_flatten(array) #=> [1, 2, 3, [4, 5]] | |
def single_flatten(array) | |
array.each do |element| | |
if element.class == Array | |
element.each {|value| results << value} | |
else | |
results << element | |
end | |
end | |
results | |
end | |
## flattening an array N times | |
## Example: | |
## array = [1, [2, 3, [4, [5, 6]]]] | |
## multiple_flatten(my_array, 2) #=> [1, 2, 3, 4, [5, 6]] | |
def multiple_flatten(array, n) | |
count = 0 | |
arr = array | |
while count < n do | |
arr = single_flatten(arr) | |
count += 1 | |
end | |
arr | |
end | |
## flattening an array with recursion | |
## Eample: | |
## array = [1, [2, 3, [4, 5]]] | |
## recursive_flatten(my_array) #=> [1, 2, 3, 4, 5] | |
def recursive_flatten(array, results = []) | |
array.each do |element| | |
if element.class == Array | |
recursive_flatten(element, results) | |
else | |
results << element | |
end | |
end | |
results | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment