Last active
May 18, 2016 19:47
-
-
Save g33kidd/54e9ffcfa226695630a14fe7246b7067 to your computer and use it in GitHub Desktop.
Array Flatten
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
# Elixir is by far one of my Favorite programming languages so I decided to write this Flattener in Elixir. | |
# It may look similar to Ruby, but it most definitely is not Ruby. | |
defmodule Flattener do | |
def flatten([]), do: [] | |
# Takes the list head and adds the tail to the end of the list | |
# this gets repeated for each nested list inside the list and | |
# keeps adding the tail of each list to the end of the flattened list. | |
def flatten([h|t]), do: flatten(h) ++ flatten(t) | |
def flatten(h), do: [h] | |
end | |
# Map of lists to Enumerate over and test. | |
lists = %{ | |
first: [[1,2,[3]],4,[5,6,[7]]], | |
second: [1,2,[3,[4,5]],6,[7,8,[9]]], | |
last: [[[1],2,3,[4,5,6]],7,[8,9,10,[11]]] | |
} | |
# Enumerate each list in the Map, Flatten the list, and output to the console. | |
Enum.each(lists, fn({key, val}) -> | |
IO.inspect RC.flatten(val) | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment