Skip to content

Commit

Permalink
Fixed out of memory error in shrinking.
Browse files Browse the repository at this point in the history
See #525
  • Loading branch information
jlink committed Nov 15, 2023
1 parent 5a2a12a commit c6a2d5b
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 7 deletions.
48 changes: 41 additions & 7 deletions engine/src/main/java/net/jqwik/engine/support/Combinatorics.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.ArrayList;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;

import net.jqwik.api.*;
Expand Down Expand Up @@ -81,15 +82,48 @@ public static Stream<Tuple2<Integer, Integer>> distinctPairs(int maxExclusive) {
if (maxExclusive < 2) {
return Stream.empty();
}
List<Tuple2<Integer, Integer>> pairs = new ArrayList<>();
for (int i = 0; i < maxExclusive; i++) {
for (int j = i + 1; j < maxExclusive; j++) {
if (i != j) {
pairs.add(Tuple.of(i, j));
}
return StreamSupport.stream(new PairSpliterator(maxExclusive), false);
}

private static class PairSpliterator implements Spliterator<Tuple2<Integer, Integer>> {
private final int maxExclusive;

private int i = 0;
private int j = 1;

public PairSpliterator(int maxExclusive) {
this.maxExclusive = maxExclusive;
}

@Override
public boolean tryAdvance(Consumer<? super Tuple2<Integer, Integer>> action) {
if (j >= maxExclusive) {
return false;
}
action.accept(Tuple.of(i, j));
j += 1;
if (j >= maxExclusive) {
i += 1;
j = i + 1;
}
return true;
}

@Override
public Spliterator<Tuple2<Integer, Integer>> trySplit() {
return null;
}

@Override
public long estimateSize() {
return (long) maxExclusive * (maxExclusive - 1) / 2;
}

@Override
public int characteristics() {
return Spliterator.DISTINCT | Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL | Spliterator.IMMUTABLE;
}
return pairs.stream();
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.util.stream.*;

import net.jqwik.api.*;
import net.jqwik.api.Tuple.*;
import net.jqwik.api.constraints.*;

import static java.util.Arrays.*;
Expand All @@ -27,6 +28,24 @@ <T> void concatenatingIterables(@ForAll @Size(max = 10) List<@Size(max = 10) Lis
assertThat(iterator.hasNext()).isFalse();
}

@Example
void distinctPairs() {
assertThat(Combinatorics.distinctPairs(0)).isEmpty();
assertThat(Combinatorics.distinctPairs(1)).isEmpty();
assertThat(Combinatorics.distinctPairs(2)).containsExactly(
Tuple.of(0, 1)
);
assertThat(Combinatorics.distinctPairs(3)).containsExactly(
Tuple.of(0, 1),
Tuple.of(0, 2),
Tuple.of(1, 2)
);
// (n * n-1) / 2:
assertThat(Combinatorics.distinctPairs(10)).hasSize(45);
assertThat(Combinatorics.distinctPairs(100)).hasSize(4950);
assertThat(Combinatorics.distinctPairs(1000)).hasSize(499500);
}

@Group
@Label("listCombinations")
class CombineList {
Expand Down

0 comments on commit c6a2d5b

Please sign in to comment.