Skip to content

Instantly share code, notes, and snippets.

@raulgd
Created March 10, 2016 23:30
Show Gist options
  • Save raulgd/5f97f6ca9288b22c830a to your computer and use it in GitHub Desktop.
Save raulgd/5f97f6ca9288b22c830a to your computer and use it in GitHub Desktop.
package codeTest;
import java.util.ArrayList;
public class App
{
public static void main( String[] args ) {
test2DArray();
test3DArray();
}
/**
* Recursively go through an array of integers and copy them to a resulting array,
* if it contains nested arrays, add its integers to the target as well.
*
* @param array an ArrayList of integers and other ArrayLists
* @param target the resulting array list of integers
*/
public static void recursiveFlatten(Object array, ArrayList<Integer> target) {
if (array instanceof ArrayList) {
for (Object item : (ArrayList) array) {
if (item instanceof ArrayList) {
recursiveFlatten(item, target);
} else if (item instanceof Integer) {
target.add((Integer) item);
}
}
}
}
/**
* Test with an arraylist that contains integers and a one-level nested arraylist
*/
public static void test2DArray() {
ArrayList<Object> one = new ArrayList<>();
ArrayList<Object> two = new ArrayList<>();
ArrayList<Integer> flatten = new ArrayList<>();
two.add(new Integer(10));
two.add(new Integer(11));
two.add(new Integer(12));
one.add(new Integer(1));
one.add(new Integer(2));
one.add(two);
one.add(new Integer(3));
recursiveFlatten(one, flatten);
System.out.println(one);
System.out.println(flatten);
}
/**
* Test with an arraylist that contains integers and a two-level nested arraylist
*/
public static void test3DArray() {
ArrayList<Object> one = new ArrayList<>();
ArrayList<Object> two = new ArrayList<>();
ArrayList<Object> three = new ArrayList<>();
ArrayList<Integer> flatten = new ArrayList<>();
three.add(new Integer(20));
three.add(new Integer(21));
three.add(new Integer(22));
two.add(new Integer(10));
two.add(three);
two.add(new Integer(11));
two.add(new Integer(12));
one.add(new Integer(1));
one.add(new Integer(2));
one.add(two);
one.add(new Integer(3));
recursiveFlatten(one, flatten);
System.out.println(one);
System.out.println(flatten);
}
}
@raulgd
Copy link
Author

raulgd commented Mar 10, 2016

This is how the result looks like on the console:

[1, 2, [10, 11, 12], 3]
[1, 2, 10, 11, 12, 3]
[1, 2, [10, [20, 21, 22], 11, 12], 3]
[1, 2, 10, 20, 21, 22, 11, 12, 3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment