Skip to content

Instantly share code, notes, and snippets.

@siddharthpolisiti
Created February 3, 2017 05:14
Show Gist options
  • Save siddharthpolisiti/acaecd5522f1e3133253a185a1369e84 to your computer and use it in GitHub Desktop.
Save siddharthpolisiti/acaecd5522f1e3133253a185a1369e84 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class FlattenArrays {
List<Integer> temp = new ArrayList<Integer>();
public int[] flatArray(Object[] input){
if(input.getClass().isArray()){
for(int i=0;i<input.length;i++){
if(!input[i].getClass().isArray()){
temp.add((Integer) input[i]);
}
else{
recursive((Object[])input[i]);
}
}
}
int[] array = new int[temp.size()];
for(int i=0;i<temp.size();i++){
array[i] = temp.get(i);
}
return array;
}
public void recursive(Object[] input){
for(int j=0;j<input.length;j++){
if(!input[j].getClass().isArray()){
temp.add((Integer) input[j]);
}
else{
recursive((Object[])input[j]);
}
}
}
public static void main(String[] args) {
Object[] array = new Object[2];
array[0] = new Object[3];
((Object[]) array[0])[0] = 1;
((Object[]) array[0])[1] = 2;
((Object[]) array[0])[2] = new Object[1];
((Object[])((Object[]) array[0])[2])[0] = 3;
array[1] = 4;
System.out.print("input : [");
for(int i=0;i<array.length;i++){
System.out.print(array[i]);
if(i<array.length-1)
System.out.print(",");
}
System.out.println("]");
System.out.println("To be clear the input is [[1,2,[3]],4]");
FlattenArrays obj = new FlattenArrays();
int[] arr = obj.flatArray(array);
System.out.print("output : [");
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]);
if(i<arr.length-1)
System.out.print(",");
}
System.out.print("]");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment