Last active
March 10, 2016 04:07
-
-
Save jayapradha/d328cd9c965e2aff972f 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
public class Flattener { | |
/** | |
* Flattens an array of arbitrarily nested arrays of integers into | |
* a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4] | |
* | |
* @param nestedNumbers - array ob objects (either plain integers or nested arrays of integers) | |
* @return - flat array of Integers | |
*/ | |
public static List<Integer> flatten(Object[] nestedNumbers) { | |
if (nestedNumbers == null) return null; | |
List<Integer> flattenedNumbers = new ArrayList<>(); | |
for (Object element : nestedNumbers) { | |
if (element instanceof Integer) { | |
flattenedNumbers.add((Integer)element); | |
} else { | |
flattenedNumbers.addAll(flatten((Object[]) element)); | |
} | |
} | |
return flattenedNumbers; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment