Last active
May 12, 2016 17:11
-
-
Save gregorydickson/746210d8ed5247b7a6134c2e61b2fce5 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
import java.util.ArrayList | |
def flatten | |
flatten = { list -> | |
switch(list){ | |
case list.size() == 0: | |
return | |
break | |
case {list.head() instanceof Integer && list.size() == 1}: | |
result = list | |
break | |
case {list.head() instanceof Integer && list.size() == 2}: | |
result = [list.head()] + flatten(list.tail()) | |
break | |
case {list.head() instanceof ArrayList && list.size() > 1}: | |
result = flatten(list.head()) + flatten(list.tail()) | |
break | |
case {list.head() instanceof ArrayList && list.size() == 1}: | |
result = flatten(list.head()) | |
break | |
case {list.head() instanceof Integer && list.size() > 1}: | |
result = [list.head()] + flatten(list.tail()) | |
break | |
case {list.head() instanceof Integer && list.size() == 1}: | |
result = [list.head()] | |
break | |
} | |
}.trampoline() | |
def newList = flatten( [[1], 2, [[3, 4], 5]]) | |
assert newList == [1, 2, 3, 4, 5] | |
println(newList) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment