Implement divideByPivot

This commit is contained in:
2021-08-29 23:36:37 +02:00
parent 7416f94dbc
commit d17c7d8de8
2 changed files with 58 additions and 2 deletions

View File

@ -442,7 +442,40 @@ public class FullyUsedArrayProcessor<T> implements SequenceProcessor<T, FullyUse
@Override
public Pair<FullyUsedArray<T>, FullyUsedArray<T>> divideByPivot(FullyUsedArray<T> array, T pivot, Comparator<T> cmp) {
throw new UnsupportedOperationException();
var p = new Pair<FullyUsedArray<T>, FullyUsedArray<T>>();
p.fst = new FullyUsedArray<>();
p.snd = new FullyUsedArray<>();
var less = 0;
var greater = 0;
for (int i = 0; i < array.theArray.length; i++) {
var c = cmp.compare(array.theArray[i], pivot);
if (c < 0) {
less++;
}
if (c > 0) {
greater++;
}
}
p.fst.theArray = Arrays.newArray(less);
p.snd.theArray = Arrays.newArray(greater);
var indexA = 0;
var indexB = 0;
for (int i = 0; i < array.theArray.length; i++) {
var c = cmp.compare(array.theArray[i], pivot);
if (c < 0) {
p.fst.theArray[indexA++] = array.theArray[i];
}
if (c > 0) {
p.snd.theArray[indexB++] = array.theArray[i];
}
}
return p;
}
@Override

View File

@ -503,7 +503,7 @@ public abstract class SequenceProcessorTest<S> {
}
@ParameterizedTest
@ArgumentsSource(DoubleListProvider.class)
@ArgumentsSource(ListProvider.class)
void testThat_divideAlternatingWorks(List<Integer> list) {
S s = processor.create(list);
var div = List.of(new ArrayList<Integer>(), new ArrayList<Integer>());
@ -520,4 +520,27 @@ public abstract class SequenceProcessorTest<S> {
assertTrue(processor.check(p.snd));
assertIterableEquals(div.get(1), processor.iterate(p.snd));
}
@ParameterizedTest
@ArgumentsSource(ListProvider.class)
void testThat_divideByPivotWorks(List<Integer> list) {
S s = processor.create(list);
var pivot = list.isEmpty() ? 50 : list.get(0);
var div = list
.stream()
.collect(Collectors.groupingBy(n ->
(int) Math.signum(cmp.compare(n, pivot))));
div.putIfAbsent(-1, List.of());
div.putIfAbsent(+1, List.of());
var p = processor.divideByPivot(s, pivot, cmp);
assertTrue(processor.check(p.fst));
assertIterableEquals(div.get(-1), processor.iterate(p.fst));
assertTrue(processor.check(p.snd));
assertIterableEquals(div.get(+1), processor.iterate(p.snd));
}
}