2

I have an array

[2,5,7,9,1,3,4,6,8]

and I want a function

List<List<Integer>> split(List<Integer> list, int n)

which will separate the list intonarrays

for example:n=4, result will be:

[2,1,8],
[5,3],
[7,4],
[9,6]

Note, the number was sampled averagely

Jimmy Guo
  • 1,288
  • 1
  • 9
  • 24

4 Answers4

3

Try this:

public static ArrayList<ArrayList<Integer>> split(ArrayList<Integer> list, int n){
    ArrayList<ArrayList<Integer>> resultArrays = new ArrayList<>();
    int pivot = 0;

    // Creates n ArrayLists.
    for(int i = 0 ; i < n ; i++){
        resultArrays.add(new ArrayList<>());
    }

    // Add element from list to new ArrayLists.
    while(pivot != list.size()){
        int p = pivot%n;
        resultArrays.get(p).add(list.get(pivot));
        pivot++;
    }

    return resultArrays;
}

The result is the one you exactly you want.

[2,1,8],
[5,3],
[7,4],
[9,6]

pivot points list's element.(from 0 to the size-1)

p points the ArrayList of ArrayList's index.(As big as n, here 4)

So,

num / *(pivot) / ArrayList[p]

1: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
    *
2: [2,5,7,9,1,3,4,6,8] -> ArrayList[1]
      *
3: [2,5,7,9,1,3,4,6,8] -> ArrayList[2]
        *
4: [2,5,7,9,1,3,4,6,8] -> ArrayList[3]
          *
5: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
            *
6: [2,5,7,9,1,3,4,6,8] -> ArrayList[1]
              *
7: [2,5,7,9,1,3,4,6,8] -> ArrayList[2]
                *
8: [2,5,7,9,1,3,4,6,8] -> ArrayList[3]
                  *
9: [2,5,7,9,1,3,4,6,8] -> ArrayList[0]
                    *
c-an
  • 3,543
  • 5
  • 35
  • 82
1

Given a number of bins.

List<List<Integer>> result = new ArrayList<>();
while(result.size()<bins){
    result.add(new ArrayList<>());
}

int counter = 0;
for(Integer i: input){
    result.get(counter++%bins).add(i);
}
matt
  • 10,892
  • 3
  • 22
  • 34
0

In Guava library there is a List.Partition method.

List<List<Integer>> split(List<Integer> list, int n) {
 return Lists.partition(list, n);
}
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
  • This is not what OP wants. Have a close look at the expected output. The order is different. – Socowi Nov 13 '18 at 09:28
0
List<List<Integer>> split(List<Integer> list, int n){
   List<List<Integer>> result = new ArrayList<>();
   //add n ArrayLists to the result list
   IntStream.range(0, n).forEach(k->result.add(new ArrayList<>()));
   //iterate over the input list and add one element to one of the inner list of the result array
   Iterator i = list.iterator();
   while(i.hasNext()){
        int count = 0;
        while(i.hasNext() && count < n){
            result.get(count).add((Integer) i.next());
            count++;
        }
   }
   return result; 
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28