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

com.redfin.fuzzy.Subcases Maven / Gradle / Ivy

package com.redfin.fuzzy;

import com.redfin.fuzzy.pairwise.Pairwise;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Subcases {

	public static  Set> map(
		Set> subcases,
		Function, Subcase> mapping
	) {
		FuzzyPreconditions.checkNotNull(subcases);
		FuzzyPreconditions.checkNotNull(mapping);

		Set> mapped = new HashSet<>(subcases.size());
		mapped.addAll(subcases.stream().map(mapping).collect(Collectors.toList()));

		return mapped;
	}

	public static  Set> mapOutput(
		Set> subcases,
		BiFunction mapping
	) {
		FuzzyPreconditions.checkNotNull(subcases);
		FuzzyPreconditions.checkNotNull(mapping);

		Function, Subcase> mapper =
			s -> (r -> mapping.apply(r, s.generate(r)));

		return subcases.stream().map(mapper).collect(Collectors.toSet());
	}

	public static  Set> mapOutput(
		Set> subcases,
		Function mapping
	) {
		FuzzyPreconditions.checkNotNull(subcases);
		FuzzyPreconditions.checkNotNull(mapping);

		Function, Subcase> mapper =
			s -> (r -> mapping.apply(s.generate(r)));

		return subcases.stream().map(mapper).collect(Collectors.toSet());
	}

	public interface BiPermutedSupplierFunction {
		R generate(Random r, T t, U u);
	}

	public static  Set> pairwisePermutations(
		Set> tSubcases,
		Set> uSubcases,
		BiPermutedSupplierFunction func
	) {
		FuzzyPreconditions.checkNotNull(func);
		FuzzyPreconditions.checkNotNull(tSubcases);
		FuzzyPreconditions.checkNotNull(uSubcases);

		List options = new ArrayList<>();
		options.add(tSubcases);
		options.add(uSubcases);

		List> permutations = (new Pairwise(options)).generate();

		return permutations.stream()
			.map(permutation -> {
				@SuppressWarnings("unchecked") Subcase tFunc = (Subcase) permutation.get(0);
				@SuppressWarnings("unchecked") Subcase uFunc = (Subcase) permutation.get(1);
				return new BiPermutedSupplier<>(func, tFunc, uFunc);
			})
			.collect(Collectors.toSet());
	}

	private static class BiPermutedSupplier implements Subcase {
		private final BiPermutedSupplierFunction func;
		private final Subcase tSubcase;
		private final Subcase uSubcase;

		public BiPermutedSupplier(BiPermutedSupplierFunction func, Subcase tSubcase, Subcase uSubcase) {
			this.func = func;
			this.tSubcase = tSubcase;
			this.uSubcase = uSubcase;
		}

		@Override
		public R generate(Random random) {
			return func.generate(random, tSubcase.generate(random), uSubcase.generate(random));
		}
	}

}