com.codepoetics.protonpack.selectors.Selectors Maven / Gradle / Ivy
package com.codepoetics.protonpack.selectors;
import java.util.Comparator;
import java.util.stream.Stream;
public final class Selectors {
private Selectors() {
}
public static Selector roundRobin() {
return new Selector() {
private int startIndex = 0;
@Override
public Integer apply(T[] options) {
int result = startIndex;
while (options[result] == null) {
result = (result + 1) % options.length;
}
startIndex = (result + 1) % options.length;
return result;
}
};
}
public static > Selector takeMin() {
return takeMin(Comparator.naturalOrder());
}
public static Selector takeMin(Comparator super T> comparator) {
return new Selector() {
private int startIndex = 0;
@Override
public Integer apply(T[] options) {
T smallest = Stream.of(options).filter(t -> t != null).min(comparator).get();
int result = startIndex;
while (options[result] == null || comparator.compare(smallest, options[result]) != 0) {
result = (result + 1) % options.length;
}
startIndex = (result + 1) % options.length;
return result;
}
};
}
public static > Selector takeMax() {
return takeMax(Comparator.naturalOrder());
}
public static Selector takeMax(Comparator super T> comparator) {
return takeMin(comparator.reversed());
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy