diff options
| author | Ben Culkin <scorpress@gmail.com> | 2020-04-13 18:40:41 -0400 |
|---|---|---|
| committer | Ben Culkin <scorpress@gmail.com> | 2020-04-13 18:40:41 -0400 |
| commit | d4ca769e542b2489b1e23cfcbdc3a0b7275b87cd (patch) | |
| tree | 1653a7399f97fb0c63ce62e3f60fd830d5c37f70 /base/src/main/java/bjc/utils/funcutils | |
| parent | 2ac2e31a56ae59ee582e43a90c3495f86dd9ee7a (diff) | |
Cleanup pass
Cleanup pass to uniformize things
Diffstat (limited to 'base/src/main/java/bjc/utils/funcutils')
18 files changed, 378 insertions, 349 deletions
diff --git a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java index fab2ba2..81313c8 100644 --- a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -15,31 +15,33 @@ public class CollectorUtils { * Create a collector that applies two collectors at once. * * @param <InitialType> - * The type of the collection to collect from. + * The type of the collection to collect from. * * @param <AuxType1> - * The intermediate type of the first collector. + * The intermediate type of the first collector. * * @param <AuxType2> - * The intermediate type of the second collector. + * The intermediate type of the second collector. * * @param <FinalType1> - * The final type of the first collector. + * The final type of the first collector. * * @param <FinalType2> - * The final type of the second collector. + * The final type of the second collector. * * @param first - * The first collector to use. + * The first collector to use. * * @param second - * The second collector to use. + * The second collector to use. * * @return A collector that functions as mentioned above. */ - public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> compoundCollect( - final Collector<InitialType, AuxType1, FinalType1> first, - final Collector<InitialType, AuxType2, FinalType2> second) { + public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> + Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, + IPair<FinalType1, FinalType2>> + compoundCollect(final Collector<InitialType, AuxType1, FinalType1> first, + final Collector<InitialType, AuxType2, FinalType2> second) { return new CompoundCollector<>(first, second); } } diff --git a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java index 555d3d1..5e51c20 100644 --- a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -18,7 +18,8 @@ import bjc.data.Pair; * @author Ben Culkin */ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, FinalType2> - implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> { + implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, + IPair<FinalType1, FinalType2>> { /* Our characteristics. */ private final Set<java.util.stream.Collector.Characteristics> characteristicSet; @@ -31,10 +32,10 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final * Create a collector that uses two collectors. * * @param first - * The first collector. + * The first collector. * * @param second - * The second collector. + * The second collector. */ public CompoundCollector(final Collector<InitialType, AuxType1, FinalType1> first, final Collector<InitialType, AuxType2, FinalType2> second) { @@ -71,27 +72,24 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final final BinaryOperator<AuxType1> firstCombiner = first.combiner(); final BinaryOperator<AuxType2> secondCombiner = second.combiner(); - return (leftState, rightState) -> { - return leftState.unwrap(leftPair -> { - return rightState.transform(rightPair -> { - return leftPair.combine(rightPair, firstCombiner, secondCombiner); - }); + return (leftState, rightState) -> leftState.unwrap(leftPair -> { + return rightState.transform(rightPair -> { + return leftPair.combine(rightPair, firstCombiner, secondCombiner); }); - }; + }); } @Override - public Function<IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> finisher() { - return state -> { - return state.unwrap(pair -> { - return pair.bind((left, right) -> { - final FinalType1 finalLeft = first.finisher().apply(left); - final FinalType2 finalRight = second.finisher().apply(right); + public Function<IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> + finisher() { + return state -> state.unwrap(pair -> { + return pair.bind((left, right) -> { + final FinalType1 finalLeft = first.finisher().apply(left); + final FinalType2 finalRight = second.finisher().apply(right); - return new Pair<>(finalLeft, finalRight); - }); + return new Pair<>(finalLeft, finalRight); }); - }; + }); } @Override diff --git a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java index 37ebd50..e8898ca 100644 --- a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -16,29 +16,29 @@ public class EnumUtils { * Do an action for a random number of enum values. * * @param <E> - * The type of the enum. + * The type of the enum. * * @param clasz - * The enum class. + * The enum class. * * @param nValues - * The number of values to execute the action on. + * The number of values to execute the action on. * * @param action - * The action to perform on random values. + * The action to perform on random values. * * @param rnd - * The source of randomness to use. + * The source of randomness to use. */ - public static <E extends Enum<E>> void doForValues(final Class<E> clasz, final int nValues, - final Consumer<E> action, final Random rnd) { + public static <E extends Enum<E>> void doForValues(final Class<E> clasz, + final int nValues, final Consumer<E> action, final Random rnd) { final E[] enumValues = clasz.getEnumConstants(); final IList<E> valueList = new FunctionalList<>(enumValues); final int randomValueCount = enumValues.length - nValues; - for(int i = 0; i <= randomValueCount; i++) { + for (int i = 0; i <= randomValueCount; i++) { final E rDir = valueList.randItem(rnd::nextInt); valueList.removeMatching(rDir); @@ -51,17 +51,18 @@ public class EnumUtils { * Get a random value from an enum. * * @param <E> - * The type of the enum. + * The type of the enum. * * @param clasz - * The class of the enum. + * The class of the enum. * * @param rnd - * The random source to use. + * The random source to use. * * @return A random value from the specified enum. */ - public static <E extends Enum<E>> E getRandomValue(final Class<E> clasz, final Random rnd) { + public static <E extends Enum<E>> E getRandomValue(final Class<E> clasz, + final Random rnd) { final E[] enumValues = clasz.getEnumConstants(); return new FunctionalList<>(enumValues).randItem(rnd::nextInt); diff --git a/base/src/main/java/bjc/utils/funcutils/FileUtils.java b/base/src/main/java/bjc/utils/funcutils/FileUtils.java index 04ac6b0..477e395 100644 --- a/base/src/main/java/bjc/utils/funcutils/FileUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/FileUtils.java @@ -14,30 +14,31 @@ import java.util.function.BiPredicate; public class FileUtils { /* * @NOTE - * - * If it becomes necessary, write another overload for this with all the - * buttons and knobs from walkFileTree. + * + * If it becomes necessary, write another overload for this with all the buttons + * and knobs from walkFileTree. */ /** * Traverse a directory recursively. This is a depth-first traversal. * * @param root - * The directory to start the traversal at. + * The directory to start the traversal at. * * @param predicate - * The predicate to determine whether or not to traverse - * a directory. + * The predicate to determine whether or not to traverse a + * directory. * * @param action - * The action to invoke upon each file in the directory. - * Returning true means to continue the traversal, - * returning false stops it. + * The action to invoke upon each file in the directory. + * Returning true means to continue the traversal, returning + * false stops it. * * @throws IOException - * If the walk throws an exception. + * If the walk throws an exception. * */ - public static void traverseDirectory(final Path root, final BiPredicate<Path, BasicFileAttributes> predicate, + public static void traverseDirectory(final Path root, + final BiPredicate<Path, BasicFileAttributes> predicate, final BiPredicate<Path, BasicFileAttributes> action) throws IOException { Files.walkFileTree(root, new FunctionalFileVisitor(predicate, action)); } diff --git a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java index ff9fefb..70e521a 100644 --- a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -13,38 +13,35 @@ import java.util.function.UnaryOperator; */ public class FuncUtils { /** - * Convert a binary function into a unary function that returns a - * function. + * Convert a binary function into a unary function that returns a function. * * @param <A> - * The initial type of the function. + * The initial type of the function. * * @param <B> - * The intermediate type of the function. + * The intermediate type of the function. * * @param <C> - * The terminal type of the function. + * The terminal type of the function. * * @param func - * The function to transform. + * The function to transform. * - * @return The function transformed into a unary function returning a - * function. + * @return The function transformed into a unary function returning a function. */ - public static <A, B, C> Function<A, Function<B, C>> curry2(final BiFunction<A, B, C> func) { - return arg1 -> arg2 -> { - return func.apply(arg1, arg2); - }; + public static <A, B, C> Function<A, Function<B, C>> + curry2(final BiFunction<A, B, C> func) { + return arg1 -> arg2 -> func.apply(arg1, arg2); } /** * Do the specified action the specified number of times. * * @param nTimes - * The number of times to do the action. + * The number of times to do the action. * * @param cons - * The action to perform. + * The action to perform. */ public static void doTimes(final int nTimes, final Consumer<Integer> cons) { for (int i = 0; i < nTimes; i++) { @@ -56,36 +53,37 @@ public class FuncUtils { * Return an operator that executes until it converges. * * @param op - * The operator to execute. + * The operator to execute. * * @param maxTries - * The maximum amount of times to apply the function in - * an attempt to cause it to converge. - * + * The maximum amount of times to apply the function in an + * attempt to cause it to converge. + * * @return The requested operator. */ - public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, final int maxTries) { - return converge(op, (nw, old) -> nw.equals(old), maxTries); + public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, + final int maxTries) { + return converge(op, Object::equals, maxTries); } /** * Return an operator that executes until it converges. * * @param op - * The operator to execute. + * The operator to execute. * @param converged - * The predicate to execute to check if the function has - * converged. + * The predicate to execute to check if the function has + * converged. * * @param maxTries - * The maximum amount of times to apply the function in - * an attempt to cause it to converge. - * + * The maximum amount of times to apply the function in an + * attempt to cause it to converge. + * * @return The requested operator. */ - public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, final BiPredicate<T, T> converged, - final int maxTries) { - return (val) -> { + public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, + final BiPredicate<T, T> converged, final int maxTries) { + return val -> { T newVal = op.apply(val); T oldVal; diff --git a/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java b/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java index fb2a697..c297465 100644 --- a/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java +++ b/base/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java @@ -22,10 +22,10 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { * Create a new file visitor, powered by functions. * * @param predicate - * The predicate to use to pick which files to traverse. + * The predicate to use to pick which files to traverse. * * @param action - * The function to execute on every file. + * The function to execute on every file. */ public FunctionalFileVisitor(final BiPredicate<Path, BasicFileAttributes> predicate, final BiPredicate<Path, BasicFileAttributes> action) { @@ -34,15 +34,19 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { } @Override - public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { - if(predicate.test(dir, attrs)) return FileVisitResult.CONTINUE; + public FileVisitResult preVisitDirectory(final Path dir, + final BasicFileAttributes attrs) throws IOException { + if (predicate.test(dir, attrs)) + return FileVisitResult.CONTINUE; return FileVisitResult.SKIP_SUBTREE; } @Override - public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { - if(action.test(file, attrs)) return FileVisitResult.CONTINUE; + public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) + throws IOException { + if (action.test(file, attrs)) + return FileVisitResult.CONTINUE; return FileVisitResult.TERMINATE; } diff --git a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java index 455fbf8..681d707 100644 --- a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java @@ -12,7 +12,7 @@ import bjc.funcdata.IList; * @author ben * * @param <E> - * The type of element in the list being partitioned + * The type of element in the list being partitioned */ final class GroupPartIteration<E> implements Consumer<E> { /* The list we're returning. */ @@ -35,21 +35,21 @@ final class GroupPartIteration<E> implements Consumer<E> { * Create a new group partitioning iteration. * * @param returned - * The list containing all of the existing partitions. + * The list containing all of the existing partitions. * * @param rejects - * The items that have been rejected from a partition for being - * too large. + * The items that have been rejected from a partition for being + * too large. * * @param nPerPart - * The combined value of items that should go into each - * partition. + * The combined value of items that should go into each + * partition. * * @param eleCount - * The function to use to determine the value of an item. + * The function to use to determine the value of an item. */ - public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, final int nPerPart, - final Function<E, Integer> eleCount) { + public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, + final int nPerPart, final Function<E, Integer> eleCount) { this.returnedList = returned; this.rejectedItems = rejects; this.numberPerPartition = nPerPart; @@ -61,9 +61,10 @@ final class GroupPartIteration<E> implements Consumer<E> { @Override public void accept(final E value) { - final boolean shouldStartPartition = numberInCurrentPartition >= numberPerPartition; + final boolean shouldStartPartition + = numberInCurrentPartition >= numberPerPartition; - if(shouldStartPartition) { + if (shouldStartPartition) { returnedList.add(currentPartition); currentPartition = new FunctionalList<>(); @@ -71,10 +72,10 @@ final class GroupPartIteration<E> implements Consumer<E> { } else { final int currentElementCount = elementCounter.apply(value); - final boolean shouldReject = (numberInCurrentPartition - + currentElementCount) >= numberPerPartition; + final boolean shouldReject = (numberInCurrentPartition + currentElementCount) + >= numberPerPartition; - if(shouldReject) { + if (shouldReject) { rejectedItems.add(value); } else { currentPartition.add(value); diff --git a/base/src/main/java/bjc/utils/funcutils/IBuilder.java b/base/src/main/java/bjc/utils/funcutils/IBuilder.java index f8dd2fc..b1a2020 100644 --- a/base/src/main/java/bjc/utils/funcutils/IBuilder.java +++ b/base/src/main/java/bjc/utils/funcutils/IBuilder.java @@ -6,7 +6,7 @@ package bjc.utils.funcutils; * @author ben * * @param <E> - * The type of object being built. + * The type of object being built. */ public interface IBuilder<E> { /** @@ -15,8 +15,8 @@ public interface IBuilder<E> { * @return The built object. * * @throws IllegalStateException - * If the data in the builder cannot be built into its - * corresponding object at this point in time. + * If the data in the builder cannot be built into + * its corresponding object at this point in time. */ public E build(); @@ -24,9 +24,11 @@ public interface IBuilder<E> { * Reset the state of this builder to its initial state. * * @throws UnsupportedOperationException - * If the builder doesn't support resetting its state. + * If the builder doesn't support + * resetting its state. */ public default void reset() { - throw new UnsupportedOperationException("Builder doesn't support state resetting"); + throw new UnsupportedOperationException( + "Builder doesn't support state resetting"); } } diff --git a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java index 9559540..c219d7f 100644 --- a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java +++ b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java @@ -4,14 +4,14 @@ import java.util.function.Function; /** * A pair of functions to transform between a pair of types. - * + * * @author bjculkin - * + * * @param <S> - * The source type of the isomorphism. - * + * The source type of the isomorphism. + * * @param <D> - * The destination type of isomorphism. + * The destination type of isomorphism. */ public class Isomorphism<S, D> { /* The function to the destination type. */ @@ -21,12 +21,12 @@ public class Isomorphism<S, D> { /** * Create a new isomorphism. - * + * * @param to - * The 'forward' function, from the source to the definition. - * + * The 'forward' function, from the source to the definition. + * * @param from - * The 'backward' function, from the definition to the source. + * The 'backward' function, from the definition to the source. */ public Isomorphism(Function<S, D> to, Function<D, S> from) { toFunc = to; @@ -35,10 +35,10 @@ public class Isomorphism<S, D> { /** * Apply the isomorphism forward. - * + * * @param val - * The source value. - * + * The source value. + * * @return The destination value. */ public D to(S val) { @@ -47,10 +47,10 @@ public class Isomorphism<S, D> { /** * Apply the isomorphism backward. - * + * * @param val - * The destination value. - * + * The destination value. + * * @return The source value. */ public S from(D val) { diff --git a/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java b/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java index 2b5fc57..a97e876 100644 --- a/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java @@ -7,20 +7,21 @@ import bjc.data.ArrayIterator; /** * Utility methods for dealing with iterators. - * + * * @author bjculkin * */ public class IteratorUtils { /** * A chain iterator. This is essentially flatMap in iterator form. + * * @author bjculkin * - * @param <T1> - * The type of the input values. - * - * @param <T2> - * The type of the output values. + * @param <T1> + * The type of the input values. + * + * @param <T2> + * The type of the output values. */ public static class ChainIterator<T1, T2> implements Iterator<T2> { private Iterator<T1> mainItr; @@ -30,23 +31,25 @@ public class IteratorUtils { /** * Create a new chain iterator. - * + * * @param mainItr - * The main iterator for input. - * + * The main iterator for input. + * * @param trans - * The transformation to use to produce the outputs. + * The transformation to use to produce the outputs. */ public ChainIterator(Iterator<T1> mainItr, Function<T1, Iterator<T2>> trans) { this.mainItr = mainItr; - this.trans = trans; + this.trans = trans; } @Override public boolean hasNext() { if (curItr != null) { - if (curItr.hasNext()) return true; - else return mainItr.hasNext(); + if (curItr.hasNext()) + return true; + else + return mainItr.hasNext(); } return mainItr.hasNext(); @@ -64,9 +67,9 @@ public class IteratorUtils { /** * Convert an iterator to an iterable. - * + * * @param itr - * The iterator to convert. + * The iterator to convert. * * @return An iterable that gives back that iterator. */ @@ -76,9 +79,9 @@ public class IteratorUtils { /** * Convert an iterable to an iterator. - * + * * @param itr - * The iterable to convert. + * The iterable to convert. * * @return The iterator from that iterable */ @@ -90,7 +93,7 @@ public class IteratorUtils { * Convert an array to an iterator. * * @param parms - * The array to iterate over. + * The array to iterate over. * * @return An iterator over the provided array. */ @@ -101,16 +104,17 @@ public class IteratorUtils { /** * Create a chain iterator. - * + * * @param itrA - * The iterator for input values. - * + * The iterator for input values. + * * @param itrB - * The transformation for output values. - * + * The transformation for output values. + * * @return A chain iterator from the provided values. */ - public static <A, B> Iterator<B> chain(Iterator<A> itrA, Function<A, Iterator<B>> itrB) { + public static <A, B> Iterator<B> chain(Iterator<A> itrA, + Function<A, Iterator<B>> itrB) { return new ChainIterator<>(itrA, itrB); } } diff --git a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java index 0130a77..f3637f9 100644 --- a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java +++ b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java @@ -26,7 +26,7 @@ public class LambdaLock { * Create a new lambda-enabled lock. * * @param lck - * The lock to wrap. + * The lock to wrap. */ public LambdaLock(final ReadWriteLock lck) { readLock = lck.readLock(); @@ -37,7 +37,7 @@ public class LambdaLock { * Execute an action with the read lock taken. * * @param supp - * The action to call. + * The action to call. * * @return The result of the action. */ @@ -55,7 +55,7 @@ public class LambdaLock { * Execute an action with the write lock taken. * * @param supp - * The action to call. + * The action to call. * * @return The result of the action. */ @@ -73,7 +73,7 @@ public class LambdaLock { * Execute an action with the read lock taken. * * @param action - * The action to call. + * The action to call. */ public void read(final Runnable action) { readLock.lock(); @@ -89,7 +89,7 @@ public class LambdaLock { * Execute an action with the write lock taken. * * @param action - * The action to call. + * The action to call. */ public void write(final Runnable action) { writeLock.lock(); diff --git a/base/src/main/java/bjc/utils/funcutils/ListUtils.java b/base/src/main/java/bjc/utils/funcutils/ListUtils.java index 0be42ed..f689d6c 100644 --- a/base/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -21,16 +21,16 @@ public class ListUtils { private static final int MAX_NTRIESPART = 50; /** - * Collapse a string of tokens into a single string without adding any - * spaces. + * Collapse a string of tokens into a single string without adding any spaces. * * @param input - * The list of tokens to collapse. + * The list of tokens to collapse. * * @return The collapsed string of tokens. */ public static String collapseTokens(final IList<String> input) { - if (input == null) throw new NullPointerException("Input must not be null"); + if (input == null) + throw new NullPointerException("Input must not be null"); return collapseTokens(input, ""); } @@ -40,14 +40,15 @@ public class ListUtils { * separator after each token. * * @param input - * The list of tokens to collapse. + * The list of tokens to collapse. * * @param seperator - * The separator to use for separating tokens. + * The separator to use for separating tokens. * * @return The collapsed string of tokens. */ - public static String collapseTokens(final IList<String> input, final String seperator) { + public static String collapseTokens(final IList<String> input, + final String seperator) { if (input == null) { throw new NullPointerException("Input must not be null"); } else if (seperator == null) { @@ -80,23 +81,23 @@ public class ListUtils { * Select a number of random items from the list without replacement. * * @param <E> - * The type of items to select. + * The type of items to select. * * @param list - * The list to select from. + * The list to select from. * * @param number - * The number of items to selet. + * The number of items to selet. * * @param rng - * A function that creates a random number from 0 to the - * desired number. + * A function that creates a random number from 0 to the desired + * number. * - * @return A new list containing the desired number of items randomly - * selected from the specified list without replacement. + * @return A new list containing the desired number of items randomly selected + * from the specified list without replacement. */ - public static <E> IList<E> drawWithoutReplacement(final IList<E> list, final int number, - final Function<Integer, Integer> rng) { + public static <E> IList<E> drawWithoutReplacement(final IList<E> list, + final int number, final Function<Integer, Integer> rng) { final IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); final int total = list.getSize(); @@ -124,20 +125,20 @@ public class ListUtils { * Select a number of random items from the list, with replacement. * * @param <E> - * The type of items to select. + * The type of items to select. * * @param list - * The list to select from. + * The list to select from. * * @param number - * The number of items to select. + * The number of items to select. * * @param rng - * A function that creates a random number from 0 to the - * desired number. + * A function that creates a random number from 0 to the desired + * number. * - * @return A new list containing the desired number of items randomly - * selected from the specified list. + * @return A new list containing the desired number of items randomly selected + * from the specified list. */ public static <E> IList<E> drawWithReplacement(final IList<E> list, final int number, final Function<Integer, Integer> rng) { @@ -151,32 +152,33 @@ public class ListUtils { } /** - * Partition a list into a list of lists, where each element can count - * for more than one element in a partition. + * Partition a list into a list of lists, where each element can count for more + * than one element in a partition. * * @param <E> - * The type of elements in the list to partition. + * The type of elements in the list to partition. * * @param input - * The list to partition. + * The list to partition. * * @param counter - * The function to determine the count for each element - * for. + * The function to determine the count for each element + * for. * * @param partitionSize - * The number of elements to put in each partition. + * The number of elements to put in each partition. * * @return A list partitioned according to the above rules. */ - public static <E> IList<IList<E>> groupPartition(final IList<E> input, final Function<E, Integer> counter, - final int partitionSize) { + public static <E> IList<IList<E>> groupPartition(final IList<E> input, + final Function<E, Integer> counter, final int partitionSize) { if (input == null) { throw new NullPointerException("Input list must not be null"); } else if (counter == null) { throw new NullPointerException("Counter must not be null"); } else if (partitionSize < 1 || partitionSize > input.getSize()) { - final String fmt = "%d is not a valid partition size. Must be between 1 and %d"; + final String fmt + = "%d is not a valid partition size. Must be between 1 and %d"; final String msg = String.format(fmt, partitionSize, input.getSize()); throw new IllegalArgumentException(msg); @@ -188,11 +190,13 @@ public class ListUtils { /* List that holds elements rejected during current pass. */ final IList<E> rejected = new FunctionalList<>(); - final GroupPartIteration<E> it = new GroupPartIteration<>(returned, rejected, partitionSize, counter); + final GroupPartIteration<E> it + = new GroupPartIteration<>(returned, rejected, partitionSize, counter); /* Run up to a certain number of passes. */ - for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART - && !rejected.isEmpty(); numberOfIterations++) { + for (int numberOfIterations = 0; + numberOfIterations < MAX_NTRIESPART && !rejected.isEmpty(); + numberOfIterations++) { input.forEach(it); if (rejected.isEmpty()) { @@ -201,10 +205,11 @@ public class ListUtils { } } - final String fmt = "Heuristic (more than %d iterations of partitioning) detected an unpartitionable list. (%s)\nThe following elements were not partitioned: %s\nCurrent group in formation: %s\nPreviously formed groups: %s\n"; + final String fmt + = "Heuristic (more than %d iterations of partitioning) detected an unpartitionable list. (%s)\nThe following elements were not partitioned: %s\nCurrent group in formation: %s\nPreviously formed groups: %s\n"; - final String msg = String.format(fmt, MAX_NTRIESPART, input.toString(), rejected.toString(), - it.currentPartition.toString(), returned.toString()); + final String msg = String.format(fmt, MAX_NTRIESPART, input.toString(), + rejected.toString(), it.currentPartition.toString(), returned.toString()); throw new IllegalArgumentException(msg); } @@ -213,10 +218,10 @@ public class ListUtils { * Merge the contents of a bunch of lists together into a single list. * * @param <E> - * The type of value in this lists. + * The type of value in this lists. * * @param lists - * The values in the lists to merge. + * The values in the lists to merge. * * @return A list containing all the elements of the lists. */ @@ -254,9 +259,11 @@ public class ListUtils { * @return The list, padded to the desired size. * * @throws IllegalArgumentException - * If the list couldn't be padded to the desired size. + * If the list couldn't be padded to the + * desired size. */ - public static <E> IList<E> padList(final IList<E> list, final Function<E, Integer> counter, final int size, + public static <E> IList<E> padList(final IList<E> list, + final Function<E, Integer> counter, final int size, final Supplier<E> padder) { int count = 0; @@ -289,7 +296,8 @@ public class ListUtils { } if (threshold > MAX_NTRIESPART) { - final String fmt = "Heuristic (more than %d iterations of attempting to pad) detected an unpaddable list. (%s)\nPartially padded list: %S"; + final String fmt + = "Heuristic (more than %d iterations of attempting to pad) detected an unpaddable list. (%s)\nPartially padded list: %S"; final String msg = String.format(fmt, MAX_NTRIESPART, list.toString(), returned.toString()); @@ -303,9 +311,9 @@ public class ListUtils { /** * Convert a list of longs into an array of longs. - * + * * @param list - * The list to convert. + * The list to convert. * @return The list as an array. */ public static long[] toPrimitive(List<Long> list) { @@ -324,11 +332,10 @@ public class ListUtils { /** * Generate all of the permuations of a list. * - * This is a version of Algorith P (Plain Changes) from Knuth (vol 4A, - * pg 322) + * This is a version of Algorith P (Plain Changes) from Knuth (vol 4A, pg 322) * * @param list - * The list to generate permutations from. + * The list to generate permutations from. * @return The list of permutations of the list. */ public static <T> List<List<T>> permuteList(List<T> list) { @@ -396,7 +403,8 @@ public class ListUtils { } if (q == j) { - if (j == 0) break; + if (j == 0) + break; s += 1; diff --git a/base/src/main/java/bjc/utils/funcutils/NumberUtils.java b/base/src/main/java/bjc/utils/funcutils/NumberUtils.java index c29fafe..a5a046a 100644 --- a/base/src/main/java/bjc/utils/funcutils/NumberUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/NumberUtils.java @@ -12,22 +12,22 @@ public class NumberUtils { * Compute the falling factorial of a number. * * @param value - * The number to compute. + * The number to compute. * * @param power - * The power to do the falling factorial for. + * The power to do the falling factorial for. * * @return The falling factorial of the number to the power. */ public static int fallingFactorial(final int value, final int power) { - if(power == 0) { + if (power == 0) { return 1; - } else if(power == 1) { + } else if (power == 1) { return value; } else { int result = 1; - for(int currentSub = 0; currentSub < power + 1; currentSub++) { + for (int currentSub = 0; currentSub < power + 1; currentSub++) { result *= value - currentSub; } @@ -39,17 +39,18 @@ public class NumberUtils { * Evaluates a linear probability distribution. * * @param winning - * The number of winning possibilities. + * The number of winning possibilities. * * @param total - * The number of total possibilities. + * The number of total possibilities. * * @param rng - * The function to use to generate a random possibility. + * The function to use to generate a random possibility. * * @return Whether or not a random possibility was a winning one. */ - public static boolean isProbable(final int winning, final int total, final Function<Integer, Integer> rng) { + public static boolean isProbable(final int winning, final int total, + final Function<Integer, Integer> rng) { return rng.apply(total) < winning; } @@ -57,13 +58,13 @@ public class NumberUtils { * Check if a number is in an inclusive range. * * @param min - * The minimum value of the range. + * The minimum value of the range. * * @param max - * The maximum value of the range. + * The maximum value of the range. * * @param i - * The number to check. + * The number to check. * * @return Whether the number is in the range. */ diff --git a/base/src/main/java/bjc/utils/funcutils/SetUtils.java b/base/src/main/java/bjc/utils/funcutils/SetUtils.java index d57ac00..83c191b 100644 --- a/base/src/main/java/bjc/utils/funcutils/SetUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/SetUtils.java @@ -7,17 +7,20 @@ import java.util.Set; /** * Various utility functions dealing with sets. + * * @author bjculkin * */ public class SetUtils { /** * Create a power-set (set of all subsets) of a given set. - * @param originalSet The set to create a power-set of. + * + * @param originalSet + * The set to create a power-set of. * @return The power-set of the set. */ public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { - Set<Set<T>> sets = new HashSet<Set<T>>(); + Set<Set<T>> sets = new HashSet<>(); // Special-case empty input if (originalSet.isEmpty()) { @@ -25,18 +28,18 @@ public class SetUtils { return sets; } - List<T> list = new ArrayList<T>(originalSet); + List<T> list = new ArrayList<>(originalSet); // Add original set to list. T head = list.get(0); // Trim leading element from set. - Set<T> rest = new HashSet<T>(list.subList(1, list.size())); + Set<T> rest = new HashSet<>(list.subList(1, list.size())); Set<Set<T>> remSets = powerSet(rest); - + for (Set<T> set : remSets) { - Set<T> newSet = new HashSet<T>(); + Set<T> newSet = new HashSet<>(); // Create a new set with the removed element. newSet.add(head); @@ -51,14 +54,16 @@ public class SetUtils { /** * Utility method for set construction. - * @param elms The elements to stick in the set. + * + * @param elms + * The elements to stick in the set. * @return A set containing the specified elements. */ @SafeVarargs public static <T> Set<T> toSet(T... elms) { Set<T> set = new HashSet<>(); - for(T elm : elms) { + for (T elm : elms) { set.add(elm); } diff --git a/base/src/main/java/bjc/utils/funcutils/StringUtils.java b/base/src/main/java/bjc/utils/funcutils/StringUtils.java index 88c418f..b7a6835 100644 --- a/base/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -26,27 +26,26 @@ public class StringUtils { * expression. * * @param input - * The string to check. + * The string to check. * * @param rRegex - * The regex to see if the string only contains matches - * of. + * The regex to see if the string only contains matches of. * - * @return Whether or not the string consists only of multiple matches - * of the provided regex. + * @return Whether or not the string consists only of multiple matches of the + * provided regex. */ public static boolean containsOnly(final String input, final String rRegex) { if (input == null) throw new NullPointerException("Input must not be null"); - else if (rRegex == null) throw new NullPointerException("Regex must not be null"); + else if (rRegex == null) + throw new NullPointerException("Regex must not be null"); /* * This regular expression is fairly simple. * - * First, we match the beginning of the string. Then, we start a - * non-capturing group whose contents are the passed in regex. - * That group is then matched one or more times and the pattern - * matches to the end of the string. + * First, we match the beginning of the string. Then, we start a non-capturing + * group whose contents are the passed in regex. That group is then matched one + * or more times and the pattern matches to the end of the string. */ return input.matches("\\A(?:" + rRegex + ")+\\Z"); } @@ -67,17 +66,15 @@ public class StringUtils { } /** - * Print out a deque with a special case for easily showing a deque is - * empty. + * Print out a deque with a special case for easily showing a deque is empty. * * @param <ContainedType> - * The type in the deque. + * The type in the deque. * * @param queue - * The deque to print. + * The deque to print. * - * @return A string version of the deque, with allowance for an empty - * deque. + * @return A string version of the deque, with allowance for an empty deque. */ public static <ContainedType> String printDeque(final Deque<ContainedType> queue) { return queue.isEmpty() ? "(none)" : queue.toString(); @@ -90,16 +87,18 @@ public class StringUtils { * The sequence to convert to an English list. * * @param join - * The string to use for separating the last element from - * the rest. + * The string to use for separating the last element from the + * rest. * * @param comma * The string to use as a comma * * @return The sequence as an English list. */ - public static String toEnglishList(final Object[] objects, final String join, final String comma) { - if (objects == null) throw new NullPointerException("Sequence must not be null"); + public static String toEnglishList(final Object[] objects, final String join, + final String comma) { + if (objects == null) + throw new NullPointerException("Sequence must not be null"); final StringBuilder sb = new StringBuilder(); @@ -107,35 +106,35 @@ public class StringUtils { final String coma = comma; switch (objects.length) { - case 0: - /* Empty list. */ - break; - case 1: - /* One item. */ - sb.append(objects[0].toString()); - break; - case 2: - /* Two items. */ - sb.append(objects[0].toString()); - sb.append(" " + joiner + " "); - sb.append(objects[1].toString()); - break; - default: - /* Three or more items. */ - for (int i = 0; i < objects.length - 1; i++) { - sb.append(objects[i].toString()); - sb.append(coma + " "); - } + case 0: + /* Empty list. */ + break; + case 1: + /* One item. */ + sb.append(objects[0].toString()); + break; + case 2: + /* Two items. */ + sb.append(objects[0].toString()); + sb.append(" " + joiner + " "); + sb.append(objects[1].toString()); + break; + default: + /* Three or more items. */ + for (int i = 0; i < objects.length - 1; i++) { + sb.append(objects[i].toString()); + sb.append(coma + " "); + } - /* - * Uncomment this to remove serial commas. - * - * int lc = sb.length() - 1; - * - * sb.delete(lc - coma.length(), lc); - */ - sb.append(joiner + " "); - sb.append(objects[objects.length - 1].toString()); + /* + * Uncomment this to remove serial commas. + * + * int lc = sb.length() - 1; + * + * sb.delete(lc - coma.length(), lc); + */ + sb.append(joiner + " "); + sb.append(objects[objects.length - 1].toString()); } return sb.toString(); @@ -148,8 +147,8 @@ public class StringUtils { * The sequence to convert to an English list. * * @param join - * The string to use for separating the last element from - * the rest. + * The string to use for separating the last element from the + * rest. * * @return The sequence as an English list. */ @@ -169,7 +168,9 @@ public class StringUtils { * @return The sequence as an English list. */ public static String toEnglishList(final Object[] objects, final boolean and) { - if (and) { return toEnglishList(objects, "and"); } + if (and) { + return toEnglishList(objects, "and"); + } return toEnglishList(objects, "or"); } @@ -178,7 +179,7 @@ public class StringUtils { * Count the number of graphemes in a string. * * @param value - * The string to check. + * The string to check. * * @return The number of graphemes in the string. */ @@ -216,12 +217,12 @@ public class StringUtils { /** * Get a substring until a specified string. - * + * * @param strang - * The string to substring. + * The string to substring. * @param vx - * The place to substring until. - * + * The place to substring until. + * * @return The specified substring. */ public static String substringTo(String strang, String vx) { @@ -230,22 +231,23 @@ public class StringUtils { /** * Get a substring until a specified string. - * + * * @param strang - * The string to substring. + * The string to substring. * @param vx - * The place to substring until. + * The place to substring until. * @param allowFail - * Whether or not to allow failure. - * - * @return The specified substring, or null if the specified place to - * substring to was not found, and we were not allowed to fail. + * Whether or not to allow failure. + * + * @return The specified substring, or null if the specified place to substring + * to was not found, and we were not allowed to fail. */ public static String substringTo(String strang, String vx, boolean allowFail) { int idx = strang.indexOf(vx); if (idx == -1) { - if (allowFail) return strang; + if (allowFail) + return strang; return null; } @@ -254,11 +256,11 @@ public class StringUtils { } /** - * Split a line into a series of space-separated arguments, including - * string literals. - * + * Split a line into a series of space-separated arguments, including string + * literals. + * * @param com - * The command to split from + * The command to split from * @return The split arguments. */ public static List<String> processArguments(String com) { @@ -283,7 +285,7 @@ public class StringUtils { private Scanner scn; public boolean processComments; - public String commentInd; + public String commentInd; public boolean skipBlanks; @@ -304,13 +306,16 @@ public class StringUtils { boolean doLoop = true; do { - if (!scn.hasNextLine()) break; + if (!scn.hasNextLine()) + break; tmp = scn.nextLine().trim(); // Skip blank lines - if (skipBlanks && tmp.equals("")) continue; - if (processComments && tmp.startsWith(commentInd)) continue; + if (skipBlanks && tmp.equals("")) + continue; + if (processComments && tmp.startsWith(commentInd)) + continue; doLoop = tmp.endsWith("\\") && !tmp.endsWith("\\\\"); @@ -329,7 +334,7 @@ public class StringUtils { * Read a series of lines from an input source. * * @param scn - * The source to read the lines from. + * The source to read the lines from. * * @return An iterator over the lines from the input source. */ @@ -341,24 +346,25 @@ public class StringUtils { * Read a series of lines from an input source. * * @param scn - * The source to read the lines from. + * The source to read the lines from. * * @param processComments - * Whether or not to skip comment lines. + * Whether or not to skip comment lines. * * @param commentInd - * Indicator for starting comment lines. + * Indicator for starting comment lines. * * @param skipBlanks - * Whether or not to skip blank lines. + * Whether or not to skip blank lines. * * @return An iterator over the lines from the input source. */ - public static Iterator<String> readLines(Scanner scn, boolean processComments, String commentInd, boolean skipBlanks) { + public static Iterator<String> readLines(Scanner scn, boolean processComments, + String commentInd, boolean skipBlanks) { LineIterator itr = new LineIterator(scn); itr.processComments = processComments; - itr.commentInd = commentInd; + itr.commentInd = commentInd; itr.skipBlanks = skipBlanks; @@ -368,13 +374,12 @@ public class StringUtils { /** * Check if a string contains any one of a specified number of things, * respecting groups. - * + * * @param haystack - * The string to look in. + * The string to look in. * @param needles - * The strings to look for. - * @return Whether or not any of the strings were contained outside of - * groups. + * The strings to look for. + * @return Whether or not any of the strings were contained outside of groups. */ public static boolean levelContains(String haystack, String... needles) { return LevelSplitter.def.levelContains(haystack, needles); @@ -382,13 +387,13 @@ public class StringUtils { /** * Split a string, respecting groups. - * + * * @param phrase - * The string to split. + * The string to split. * @param splits - * The strings to split on. - * @return A list of split strings. If keepDelims is true, it also - * includes the delimiters in between the split strings. + * The strings to split on. + * @return A list of split strings. If keepDelims is true, it also includes the + * delimiters in between the split strings. */ public static List<String> levelSplit(String phrase, String... splits) { return LevelSplitter.def.levelSplit(phrase, false, splits); @@ -396,18 +401,18 @@ public class StringUtils { /** * Split a string, respecting groups. - * + * * @param phrase - * The string to split. + * The string to split. * @param keepDelims - * Whether or not to include the delimiters in the - * results. + * Whether or not to include the delimiters in the results. * @param splits - * The strings to split on. - * @return A list of split strings. If keepDelims is true, it also - * includes the delimiters in between the split strings. + * The strings to split on. + * @return A list of split strings. If keepDelims is true, it also includes the + * delimiters in between the split strings. */ - public static List<String> levelSplit(String phrase, boolean keepDelims, String... splits) { + public static List<String> levelSplit(String phrase, boolean keepDelims, + String... splits) { return LevelSplitter.def.levelSplit(phrase, keepDelims, splits); } } diff --git a/base/src/main/java/bjc/utils/funcutils/TestUtils.java b/base/src/main/java/bjc/utils/funcutils/TestUtils.java index c037ec4..3aa20a2 100644 --- a/base/src/main/java/bjc/utils/funcutils/TestUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/TestUtils.java @@ -7,18 +7,18 @@ import java.util.List; /** * Utilities for testing. - * + * * @author bjculkin * */ public class TestUtils { /** * Assert an iterator provides a particular sequence of values. - * + * * @param src - * The iterator to pull values from. + * The iterator to pull values from. * @param vals - * The values to expect from the iterator. + * The values to expect from the iterator. */ @SafeVarargs public static <T> void assertIteratorEquals(Iterator<T> src, T... vals) { @@ -29,7 +29,7 @@ public class TestUtils { /** * Assert an iterator provides a particular sequence of values. - * + * * @param src * The iterator to pull values from. * @param hasMore @@ -38,14 +38,14 @@ public class TestUtils { * The values to expect from the iterator. */ @SafeVarargs - public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src, T... vals) { + public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src, + T... vals) { /* * @NOTE - * - * Even though it's awkward, the boolean has to come first. - * Otherwise, there are cases where the compiler will get - * confused as to what the right value for T is, and be unable - * to pick an overload. + * + * Even though it's awkward, the boolean has to come first. Otherwise, there are + * cases where the compiler will get confused as to what the right value for T + * is, and be unable to pick an overload. */ assertIteratorEquals(src, vals); @@ -54,12 +54,12 @@ public class TestUtils { /** * Assert that a list has a given set of contents. - * - * @param src - * The list of actual elements. - * + * + * @param src + * The list of actual elements. + * * @param exps - * The list of expected elements. + * The list of expected elements. */ @SafeVarargs public static <T> void assertListEquals(List<T> src, T... exps) { diff --git a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java index bbb9153..d525773 100644 --- a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java @@ -14,13 +14,12 @@ import bjc.funcdata.IList; */ public class TreeUtils { /** - * Convert a tree into a list of outline nodes that match a certain - * path. - * + * Convert a tree into a list of outline nodes that match a certain path. + * * @param tre - * The tree to outline. + * The tree to outline. * @param leafMarker - * The path to mark nodes with. + * The path to mark nodes with. * @return The list of marked paths. */ public static <T> IList<IList<T>> outlineTree(ITree<T> tre, Predicate<T> leafMarker) { @@ -29,19 +28,19 @@ public class TreeUtils { LinkedList<T> path = new LinkedList<>(); path.add(tre.getHead()); - tre.doForChildren((child) -> findPath(child, path, leafMarker, paths)); + tre.doForChildren(child -> findPath(child, path, leafMarker, paths)); return paths; } /* Find a path in a tree. */ - private static <T> void findPath(ITree<T> subtree, LinkedList<T> path, Predicate<T> leafMarker, - IList<IList<T>> paths) { - if(subtree.getChildrenCount() == 0 && leafMarker.test(subtree.getHead())) { + private static <T> void findPath(ITree<T> subtree, LinkedList<T> path, + Predicate<T> leafMarker, IList<IList<T>> paths) { + if (subtree.getChildrenCount() == 0 && leafMarker.test(subtree.getHead())) { /* We're at a matching leaf node. Add it. */ IList<T> finalPath = new FunctionalList<>(); - for(T ePath : path) { + for (T ePath : path) { finalPath.add(ePath); } @@ -52,7 +51,7 @@ public class TreeUtils { /* Check the children of this node. */ path.add(subtree.getHead()); - subtree.doForChildren((child) -> findPath(child, path, leafMarker, paths)); + subtree.doForChildren(child -> findPath(child, path, leafMarker, paths)); path.removeLast(); } diff --git a/base/src/main/java/bjc/utils/funcutils/TriConsumer.java b/base/src/main/java/bjc/utils/funcutils/TriConsumer.java index 7b15097..8a0832c 100644 --- a/base/src/main/java/bjc/utils/funcutils/TriConsumer.java +++ b/base/src/main/java/bjc/utils/funcutils/TriConsumer.java @@ -6,13 +6,13 @@ package bjc.utils.funcutils; * @author EVE * * @param <A> - * Type of the first argument. + * Type of the first argument. * * @param <B> - * Type of the second argument. + * Type of the second argument. * * @param <C> - * Type of the third argument. + * Type of the third argument. */ @FunctionalInterface public interface TriConsumer<A, B, C> { @@ -20,13 +20,13 @@ public interface TriConsumer<A, B, C> { * Perform the action. * * @param a - * The first parameter. + * The first parameter. * * @param b - * The second parameter. + * The second parameter. * * @param c - * The third parameter. + * The third parameter. */ public void accept(A a, B b, C c); } |
