Skip to content

Instantly share code, notes, and snippets.

@gotidhavalh
Last active December 10, 2018 10:13
Show Gist options
  • Save gotidhavalh/802c6cdca02a69abe15da5324569498c to your computer and use it in GitHub Desktop.
Save gotidhavalh/802c6cdca02a69abe15da5324569498c to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers in Java
package com.citrusbyte;
import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void main(String[] args) {
/** Array to be flatten **/
Object[] inputArray = new Object[]{
new Object[]{1, 2, new Object[]{3, new Object[]{14,45,78,new Object[]{8,56,85}}}},
new Object[]{4, 22,new Object[]{11,9,29,66}, 51,33,new Object[]{18,42,new Object[]{8,new Object[]{92,50,101},85}}},
new Object[]{6,69},
new Object[]{100,}
};
Object[] flatArray = flatten(inputArray);
printArray(flatArray);
}
/**
* @param array - Array to be processed;
* @return the flat array;
*/
public static Object[] flatten(Object[] array){
List<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < array.length; j++) {
Integer a = getChildElement(array[j], list);
if(a != null) {
list.add((int) a);
}
}
return list.toArray();
}
/**
* Search the object which is an integer and add it to a list. *
* @param obj - the item from the list;
* @param list - a list which will save the integers;
* @return
*/
private static Integer getChildElement(Object obj, List<Integer> list) {
if(obj instanceof Integer){
list.add((int) obj);
return (int) obj;
}else{
Object[] a = (Object[]) obj;
for (int j = 0; j < a.length; j++) {
getChildElement(a[j], list);
}
}
return null;
}
/**
* Print the result
* @param list - flat array
*/
public static void printArray(Object[] list){
String comma= ",";
System.out.print("flatten array = {");
for (int i = 0 ; i < list.length ; i++){
if(i >= list.length - 1){
comma = "";
}
System.out.print(list[i] + comma);
}
System.out.print("};");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment