Skip to content

Instantly share code, notes, and snippets.

@saswata-dutta
Last active June 9, 2021 08:39
Show Gist options
  • Save saswata-dutta/d87962a1ceb4113ed195f35f513346e5 to your computer and use it in GitHub Desktop.
Save saswata-dutta/d87962a1ceb4113ed195f35f513346e5 to your computer and use it in GitHub Desktop.
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].
import java.util.ArrayList;
import java.util.List;
public class FlattenArray {
static List<Integer> flatten(Object[] input) {
if (input == null) return null;
List<Integer> acc = new ArrayList<>();
for (Object el : input) {
if (el instanceof Integer) {
acc.add((Integer) el);
} else if (el instanceof Object[]) {
acc.addAll(flatten((Object[]) el));
} else {
throw new IllegalArgumentException("Input must be an array of Integers or nested arrays of Integers");
}
}
return acc;
}
public static void main(String[] args) {
// [[1, [2, [3]]], 4]
Object[] a3 = {3};
Object[] a2 = {2, a3};
Object[] a1 = {1, a2};
Object[] input = {a1, 4};
System.out.println(flatten(input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment