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

net.jqwik.engine.properties.arbitraries.randomized.InjectDuplicatesGenerator Maven / Gradle / Ivy

The newest version!
package net.jqwik.engine.properties.arbitraries.randomized;

import java.util.*;

import net.jqwik.api.*;
import net.jqwik.api.lifecycle.*;
import net.jqwik.engine.*;

import org.jspecify.annotations.*;

public class InjectDuplicatesGenerator implements RandomGenerator {

	private final RandomGenerator base;
	private final double duplicateProbability;
	private final Store> previousSeedsStore;

	public InjectDuplicatesGenerator(RandomGenerator base, double duplicateProbability) {
		this.base = base;
		this.duplicateProbability = duplicateProbability;
		this.previousSeedsStore = createPreviousSeedsStorePerTry();
	}

	private Store> createPreviousSeedsStorePerTry() {
		return Store.getOrCreate(this, Lifespan.TRY, ArrayList::new);
	}

	@Override
	public Shrinkable next(Random random) {
		long seed = chooseSeed(random);
		return base.next(SourceOfRandomness.newRandom(seed));
	}

	long chooseSeed(Random random) {
		List previousSeeds = previousSeedsStore.get();
		if (!previousSeeds.isEmpty()) {
			if (random.nextDouble() <= duplicateProbability) {
				return randomPreviousSeed(previousSeedsStore, random);
			}
		}
		long seed = random.nextLong();
		previousSeeds.add(seed);
		return seed;
	}

	private long randomPreviousSeed(Store> previousSeeds, Random random) {
		int index = random.nextInt(previousSeeds.get().size());
		return previousSeeds.get().get(index);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy