Interleave List If input = [[1,2,3], [9, 0], [5], [-4,-5,-2,-3,-1]] then output = [1,9,5,-4,2,0,-5,3,-2,-3,-1];
Asked in Facebook F2F
In Python you can do it very easily
#!/usr/bin/python
max = 3 listofList = [[1, 2, 3], [9, 5], [-1], [12,90,3] ]; oplist =[]; for i in range(0,max): for list in listofList: if (i < len(list)): oplist.append(list[i]) print oplist
In Java using same logic..
import java.util.*; import java.lang.*; import java.io.*; import java.util.Arrays; import java.util.List; class Ideone { private static void interleaveLists(List<List<Integer>> ll){ if(ll == null) return; int listLength = 0; int total = 0; for(List<Integer> list : ll){ if(list == null) continue; listLength = Math.max(list.size(), listLength); total += list.size(); } int[] result = new int[total]; int index = 0; for(int i = 0; i < listLength; ++i){ for(List<Integer> list : ll){ if(list == null) continue; if(i < list.size()){ result[index++] = list.get(i); System.out.println(list.get(i)); } } } for( int x :result){ System.out.println(x); } } public static <Integer> List<Integer> twoDArrayToList(int [][] twoDArray) { List list = new ArrayList(); for (int [] array : twoDArray) { list.add(Arrays.asList(array)); } return list; } public static void main (String[] args) throws java.lang.Exception { int [][] arr = {{1, 2, 3}, {9, 0}, {5}, {-4, -5, -2, -3, -1,5,2}}; List<List<Integer>> ll = twoDArrayToList(arr); interleaveLists(ll); } }