Created
May 22, 2017 05:28
-
-
Save kotinagam/85bad7de5cd24b25e5b4522639902142 to your computer and use it in GitHub Desktop.
Java code to flatten an Array
This file contains hidden or 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
package com.myorg.agodaexercise; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
/** | |
* Flattens an array of arbitrarily nested arrays of integers into a flat array of integers. | |
* <p/> | |
* @author koti | |
*/ | |
public class FlattenIntegerArray { | |
/** | |
* Flatten 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 inputArray an array of Integers or nested arrays of Integers | |
* @return flattened array of Integers or null if input is null | |
* @throws IllegalArgumentException | |
*/ | |
public static Integer[] flatten(Object[] inputArray) throws IllegalArgumentException { | |
if (inputArray == null) return null; | |
List<Integer> flatList = new ArrayList<Integer>(); | |
for (Object element : inputArray) { | |
if (element instanceof Integer) { | |
flatList.add((Integer) element); | |
} else if (element instanceof Object[]) { | |
flatList.addAll(Arrays.asList(flatten((Object[]) element))); | |
} else { | |
throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers"); | |
} | |
// System.out.println("Flattened Array "+flatList); | |
} | |
return flatList.toArray(new Integer[flatList.size()]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment