Fix list partitioning helper.

Fixes #2934

// FREEBIE
This commit is contained in:
Moxie Marlinspike 2015-04-12 10:07:30 -07:00
parent 77e846d24e
commit b9541a65b0
2 changed files with 85 additions and 3 deletions

View File

@ -0,0 +1,83 @@
package org.thoughtcrime.securesms.util;
import java.util.LinkedList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
public class ListPartitionTest {
public void testPartitionEven() {
List<Integer> list = new LinkedList<>();
for (int i=0;i<100;i++) {
list.add(i);
}
List<List<Integer>> partitions = Util.partition(list, 10);
assertEquals(partitions.size(), 10);
int counter = 0;
for (int i=0;i<partitions.size();i++) {
List<Integer> partition = partitions.get(i);
assertEquals(partition.size(), 10);
for (int j=0;j<partition.size();j++) {
assertEquals((int)partition.get(j), counter++);
}
}
}
public void testPartitionOdd() {
List<Integer> list = new LinkedList<>();
for (int i=0;i<100;i++) {
list.add(i);
}
list.add(100);
List<List<Integer>> partitions = Util.partition(list, 10);
assertEquals(partitions.size(), 11);
int counter = 0;
for (int i=0;i<partitions.size()-1;i++) {
List<Integer> partition = partitions.get(i);
assertEquals(partition.size(), 10);
for (int j=0;j<partition.size();j++) {
assertEquals((int)partition.get(j), counter++);
}
}
assertEquals(partitions.get(10).size(), 1);
assertEquals((int)partitions.get(10).get(0), 100);
}
public void testPathological() {
List<Integer> list = new LinkedList<>();
for (int i=0;i<100;i++) {
list.add(i);
}
List<List<Integer>> partitions = Util.partition(list, 1);
assertEquals(partitions.size(), 100);
int counter = 0;
for (int i=0;i<partitions.size();i++) {
List<Integer> partition = partitions.get(i);
assertEquals(partition.size(), 1);
for (int j=0;j<partition.size();j++) {
assertEquals((int)partition.get(j), counter++);
}
}
}
}

View File

@ -201,10 +201,9 @@ public class Util {
List<List<T>> results = new LinkedList<>(); List<List<T>> results = new LinkedList<>();
for (int index=0;index<list.size();index+=partitionSize) { for (int index=0;index<list.size();index+=partitionSize) {
int offset = index * partitionSize; int subListSize = Math.min(partitionSize, list.size() - index);
int subListSize = Math.min(partitionSize, list.size() - offset);
results.add(list.subList(offset, offset + subListSize)); results.add(list.subList(index, index + subListSize));
} }
return results; return results;