All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.jqwik.engine.properties.shrinking.ListShrinkingCandidates Maven / Gradle / Ivy

There is a newer version: 1.9.1
Show newest version
package net.jqwik.engine.properties.shrinking;

import java.util.*;

public class ListShrinkingCandidates implements ShrinkingCandidates> {

	private final int minSize;

	public ListShrinkingCandidates(int minSize) {
		this.minSize = minSize;
	}

	@Override
	public Set> candidatesFor(List toShrink) {
		if (toShrink.size() <= minSize)
			return Collections.emptySet();
		Set> lists = new HashSet<>();
		appendRightCuts(toShrink, lists);
		appendLeftCuts(toShrink, lists);
		return lists;
	}

	private void appendLeftCuts(List toShrink, Set> lists) {
		int elementsToCut = calculateElementsToCut(toShrink.size());
		appendLeftCut(toShrink, lists, elementsToCut);
		if (elementsToCut != 1) {
			appendLeftCut(toShrink, lists, 1);
		}
	}

	private void appendLeftCut(List toShrink, Set> lists, int elementsToCut) {
		List leftCut = new ArrayList<>(toShrink);
		cutFromLeft(leftCut, elementsToCut);
		lists.add(leftCut);
	}

	private int calculateElementsToCut(int listSize) {
		int toCut = rawElementsToCut(listSize);
		return Math.min(toCut, listSize - minSize);
	}

	private int rawElementsToCut(int listSize) {
		// TODO: Improve cut size. Those values are purely guesses.
		// Maybe use integer shrinking to determine target size.
		if (listSize <= 10)
			return 1;
		if (listSize < 20)
			return listSize - 9;
		return listSize / 2;
	}

	private void cutFromLeft(List leftCut, int elementsToCut) {
		if (elementsToCut == 0)
			return;
		leftCut.remove(0);
		cutFromLeft(leftCut, --elementsToCut);
	}

	private void appendRightCuts(List toShrink, Set> lists) {
		int elementsToCut = calculateElementsToCut(toShrink.size());
		appendRightCut(toShrink, lists, elementsToCut);
		if (elementsToCut != 1) {
			appendRightCut(toShrink, lists, 1);
		}
	}

	private void appendRightCut(List toShrink, Set> lists, int elementsToCut) {
		List rightCut = new ArrayList<>(toShrink);
		cutFromRight(rightCut, elementsToCut);
		lists.add(rightCut);
	}

	private void cutFromRight(List rightCut, int elementsToCut) {
		if (elementsToCut == 0)
			return;
		rightCut.remove(rightCut.size() - 1);
		cutFromRight(rightCut, --elementsToCut);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy