diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-03-31 11:43:21 -0400 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2016-03-31 11:43:21 -0400 |
| commit | 8a8b457c98e207d809a7616e73eb59bfe197a7a5 (patch) | |
| tree | 36fcbb7f10e92adbfb866fced7f27af1ef89f636 /BJC-Utils2/src/main/java | |
| parent | 32b1b46fcc855fffe6b0dddd10442a9a4f1544d2 (diff) | |
More code maintenance
Diffstat (limited to 'BJC-Utils2/src/main/java')
43 files changed, 1246 insertions, 956 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java index bf49762..9d18390 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/ComponentDescriptionFileParser.java @@ -18,50 +18,50 @@ public class ComponentDescriptionFileParser { static { // This reader works entirely off of pragmas, so no need to handle // rules - reader = new RuleBasedConfigReader<>((fst, par) -> { - }, (fst, stat) -> { - }, (stat) -> { + reader = new RuleBasedConfigReader<>((tokenizer, statePair) -> { + }, (tokenizer, state) -> { + }, (state) -> { }); - reader.addPragma("name", (fst, stat) -> { - if (!fst.hasMoreTokens()) { + reader.addPragma("name", (tokenizer, state) -> { + if (!tokenizer.hasMoreTokens()) { throw new PragmaFormatException( "Pragma name requires at least one argument"); } else { - stat.setName( - ListUtils.collapseTokens(fst.toList((s) -> s))); + state.setName(ListUtils.collapseTokens( + tokenizer.toList((strang) -> strang))); } }); - reader.addPragma("author", (fst, stat) -> { - if (!fst.hasMoreTokens()) { + reader.addPragma("author", (tokenizer, state) -> { + if (!tokenizer.hasMoreTokens()) { throw new PragmaFormatException( "Pragma author requires at least one argument"); } else { - stat.setAuthor( - ListUtils.collapseTokens(fst.toList((s) -> s))); + state.setAuthor(ListUtils.collapseTokens( + tokenizer.toList((strang) -> strang))); } }); - reader.addPragma("description", (fst, stat) -> { - if (!fst.hasMoreTokens()) { + reader.addPragma("description", (tokenizer, state) -> { + if (!tokenizer.hasMoreTokens()) { throw new PragmaFormatException( "Pragma description requires at least one argument"); } else { - stat.setDescription( - ListUtils.collapseTokens(fst.toList((s) -> s))); + state.setDescription(ListUtils.collapseTokens( + tokenizer.toList((strang) -> strang))); } }); - reader.addPragma("version", (fst, stat) -> { - if (!fst.hasMoreTokens()) { + reader.addPragma("version", (tokenizer, state) -> { + if (!tokenizer.hasMoreTokens()) { throw new PragmaFormatException( "Pragma name requires at least one argument"); } else { - String token = fst.nextToken(); + String token = tokenizer.nextToken(); try { - stat.setVersion(Integer.parseInt(token)); + state.setVersion(Integer.parseInt(token)); } catch (NumberFormatException nfex) { throw new PragmaFormatException("Argument " + token + " to version pragma isn't a valid integer. " @@ -74,12 +74,15 @@ public class ComponentDescriptionFileParser { /** * Parse a component description from a stream * - * @param is + * @param inputSource * The stream to parse from * @return The description parsed from the stream */ - public static ComponentDescription fromStream(InputStream is) { - return reader.fromStream(is, new ComponentDescriptionState()) - .toDescription(); + public static ComponentDescription + fromStream(InputStream inputSource) { + ComponentDescriptionState readState = reader + .fromStream(inputSource, new ComponentDescriptionState()); + + return readState.toDescription(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java index f2d2cf8..d808b8e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/FileComponentRepository.java @@ -1,10 +1,12 @@ package bjc.utils.components; import java.io.File; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.function.Function; +import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bjc.utils.funcdata.FunctionalList; @@ -21,15 +23,18 @@ import bjc.utils.funcdata.FunctionalList; public class FileComponentRepository<E extends IDescribedComponent> implements IComponentRepository<E> { + private static final Logger CLASS_LOGGER = + LoggerFactory.getLogger(FileComponentRepository.class); + /** * The internal storage of components */ - private Map<String, E> comps; + private Map<String, E> components; /** * The path that all the components came from */ - private String sourcePath; + private Path sourceDirectory; /** * Create a new component repository sourcing components from files in @@ -39,28 +44,54 @@ public class FileComponentRepository<E extends IDescribedComponent> * cause the loading of that component to fail, but a warning will be * logged. * - * @param dir + * @param directory * The directory to read component files from - * @param reader + * @param componentReader * The function to use to convert files to components */ - public FileComponentRepository(File dir, Function<File, E> reader) { - comps = new HashMap<>(); - sourcePath = dir.getAbsolutePath(); + public FileComponentRepository(File directory, + Function<File, E> componentReader) { + if (!directory.isDirectory()) { + throw new IllegalArgumentException("File " + directory + + " is not a directory.\n" + + "Components can only be read from a directory"); + } + + components = new HashMap<>(); + sourceDirectory = directory.toPath().toAbsolutePath(); - for (File fle : dir.listFiles()) { - if (fle.isDirectory()) { + File[] listFiles = directory.listFiles(); + + if (listFiles == null) { + throw new IllegalArgumentException("File " + directory + + " is not a valid directory.\n" + + "Components can only be read from a directory"); + } + + for (File componentFile : listFiles) { + if (componentFile.isDirectory()) { // Do nothing with directories. They probably contain // support files for components } else { try { - E comp = reader.apply(fle); + E component = componentReader.apply(componentFile); - comps.put(comp.getName(), comp); + if (component == null) { + throw new NullPointerException( + "Component reader read null component"); + } else if (!components + .containsKey(component.getName())) { + components.put(component.getName(), component); + } else { + CLASS_LOGGER.warn("Found a duplicate component.\n" + + "Multiple versions of the same component are not currently supported.\n" + + "The component" + component + + " will not be registered ."); + } } catch (Exception ex) { - LoggerFactory.getLogger(getClass()) + CLASS_LOGGER .warn("Error found reading component from file " - + fle.toString() + + componentFile.toString() + ". This component will not be loaded"); } @@ -70,20 +101,26 @@ public class FileComponentRepository<E extends IDescribedComponent> @Override public FunctionalList<E> getComponentList() { - FunctionalList<E> ret = new FunctionalList<>(); + FunctionalList<E> returnedList = new FunctionalList<>(); - comps.forEach((name, comp) -> ret.add(comp)); + components + .forEach((name, component) -> returnedList.add(component)); - return ret; + return returnedList; } @Override public Map<String, E> getComponents() { - return comps; + return components; } @Override public String getSource() { - return "Components read from directory " + sourcePath + "."; + return "Components read from directory " + sourceDirectory + "."; + } + + @Override + public E getComponentByName(String name) { + return components.get(name); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java index 3e284e6..04ff51b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java +++ b/BJC-Utils2/src/main/java/bjc/utils/components/IComponentRepository.java @@ -29,6 +29,16 @@ public interface IComponentRepository<E extends IDescribedComponent> { public Map<String, E> getComponents(); /** + * Get a component with a specific name + * + * @param name + * The name of the component to retrieve + * @return The named component, or null if no component with that name + * exists + */ + public E getComponentByName(String name); + + /** * Get the source from which these components came * * @return The source from which these components came diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/GenHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/GenHolder.java index 8b1983e..6854440 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/GenHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/GenHolder.java @@ -19,24 +19,24 @@ public class GenHolder<T> implements IHolder<T> { /** * The state this holder is responsible for. */ - private T held; + private T heldValue; /** * Creates a new empty holder, with its state set to null */ public GenHolder() { - held = null; + heldValue = null; } /** * Creates a new holder, with its state initialized to the provided * value * - * @param hld + * @param held * The state to initialize this holder to. */ - public GenHolder(T hld) { - held = hld; + public GenHolder(T held) { + heldValue = held; } /* @@ -45,8 +45,8 @@ public class GenHolder<T> implements IHolder<T> { * @see bjc.utils.data.IHolder#doWith(java.util.function.Consumer) */ @Override - public void doWith(Consumer<T> f) { - f.accept(held); + public void doWith(Consumer<T> action) { + action.accept(heldValue); } /* @@ -55,8 +55,8 @@ public class GenHolder<T> implements IHolder<T> { * @see bjc.utils.data.IHolder#map(java.util.function.Function) */ @Override - public <NewT> IHolder<NewT> map(Function<T, NewT> f) { - return new GenHolder<>(f.apply(held)); + public <NewT> IHolder<NewT> map(Function<T, NewT> transformer) { + return new GenHolder<>(transformer.apply(heldValue)); } /* @@ -65,8 +65,8 @@ public class GenHolder<T> implements IHolder<T> { * @see bjc.utils.data.IHolder#transform(java.util.function.Function) */ @Override - public IHolder<T> transform(Function<T, T> f) { - held = f.apply(held); + public IHolder<T> transform(Function<T, T> transformer) { + heldValue = transformer.apply(heldValue); return this; } @@ -77,12 +77,12 @@ public class GenHolder<T> implements IHolder<T> { * @see bjc.utils.data.IHolder#unwrap(java.util.function.Function) */ @Override - public <E> E unwrap(Function<T, E> f) { - return f.apply(held); + public <E> E unwrap(Function<T, E> unwrapper) { + return unwrapper.apply(heldValue); } @Override public String toString() { - return held.toString(); + return heldValue.toString(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java index 3675842..6290d5f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IHolder.java @@ -17,10 +17,10 @@ public interface IHolder<T> { /** * Call a provided function with the value being held * - * @param f + * @param action * The function to call */ - public void doWith(Consumer<T> f); + public void doWith(Consumer<T> action); /** * Return the result of applying the given transformation to the held @@ -29,21 +29,21 @@ public interface IHolder<T> { * @param <NewT> * The new type of the held value * - * @param f + * @param transformer * The transformation to apply * @return A holder with the transformed value */ - public <NewT> IHolder<NewT> map(Function<T, NewT> f); + public <NewT> IHolder<NewT> map(Function<T, NewT> transformer); /** * Apply the given transformation to the held value. Returns the holder * for allowing chaining of transforms * - * @param f + * @param transformer * The transform to apply to the value * @return The holder */ - public IHolder<T> transform(Function<T, T> f); + public IHolder<T> transform(Function<T, T> transformer); /** * Returns a raw mapped value, not contained in a GenHolder @@ -51,9 +51,9 @@ public interface IHolder<T> { * @param <E> * The type of the value that is the end result * - * @param f + * @param unwrapper * The function to use for mapping the value * @return The mapped value outside of a GenHolder */ - public <E> E unwrap(Function<T, E> f); + public <E> E unwrap(Function<T, E> unwrapper); }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java index fcf5618..e2ee6a4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/IPair.java @@ -25,23 +25,23 @@ public interface IPair<L, R> { * @param <R2> * The new right type of the pair * - * @param lf + * @param leftTransformer * The function to apply to the left value. - * @param rf + * @param rightTransformer * The function to apply to the right value. * @return A new pair containing the two modified values. */ - public <L2, R2> IPair<L2, R2> apply(Function<L, L2> lf, - Function<R, R2> rf); + public <L2, R2> IPair<L2, R2> apply(Function<L, L2> leftTransformer, + Function<R, R2> rightTransformer); /** * Execute an action with the values of this pair. Has no effect on the * internal contents * - * @param bc + * @param action * The action to execute on the values */ - public void doWith(BiConsumer<L, R> bc); + public void doWith(BiConsumer<L, R> action); /** * Collapse this pair to a single value. Does not change the internal @@ -50,9 +50,9 @@ public interface IPair<L, R> { * @param <E> * The resulting type after merging * - * @param bf + * @param merger * The function to use to collapse the pair. * @return The collapsed value. */ - public <E> E merge(BiFunction<L, R, E> bf); + public <E> E merge(BiFunction<L, R, E> merger); }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java index 4a8fbc3..b5ad953 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java @@ -20,12 +20,12 @@ public class Pair<L, R> implements IPair<L, R> { /** * The left value of the pair */ - protected L l; + protected L leftValue; /** * The right value of the pair */ - protected R r; + protected R rightValue; /** * Create a new pair that holds two nulls. @@ -43,8 +43,8 @@ public class Pair<L, R> implements IPair<L, R> { * The value to hold on the right. */ public Pair(L left, R right) { - l = left; - r = right; + leftValue = left; + rightValue = right; } /* @@ -54,9 +54,10 @@ public class Pair<L, R> implements IPair<L, R> { * java.util.function.Function) */ @Override - public <L2, R2> IPair<L2, R2> apply(Function<L, L2> lf, - Function<R, R2> rf) { - return new Pair<>(lf.apply(l), rf.apply(r)); + public <L2, R2> IPair<L2, R2> apply(Function<L, L2> leftTransformer, + Function<R, R2> rightTransformer) { + return new Pair<>(leftTransformer.apply(leftValue), + rightTransformer.apply(rightValue)); } /* @@ -65,8 +66,8 @@ public class Pair<L, R> implements IPair<L, R> { * @see bjc.utils.data.IPair#doWith(java.util.function.BiConsumer) */ @Override - public void doWith(BiConsumer<L, R> bc) { - bc.accept(l, r); + public void doWith(BiConsumer<L, R> action) { + action.accept(leftValue, rightValue); } /* @@ -75,7 +76,7 @@ public class Pair<L, R> implements IPair<L, R> { * @see bjc.utils.data.IPair#merge(java.util.function.BiFunction) */ @Override - public <E> E merge(BiFunction<L, R, E> bf) { - return bf.apply(l, r); + public <E> E merge(BiFunction<L, R, E> merger) { + return merger.apply(leftValue, rightValue); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyHolder.java index ddf3cfc..e74ce91 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyHolder.java @@ -23,26 +23,26 @@ public class LazyHolder<T> implements IHolder<T> { private final class LazyHolderSupplier<NewT> implements Supplier<NewT> { private FunctionalList<Function<T, T>> pendingActions; - private Function<T, NewT> f; + private Function<T, NewT> pendingTransform; public LazyHolderSupplier(FunctionalList<Function<T, T>> actons, - Function<T, NewT> f) { + Function<T, NewT> transform) { // Resolve latent bug I just realized. After a map, adding new // actions to the original holder could've resulted in changes // to all unactualized mapped values from that holder pendingActions = actons.clone(); - this.f = f; + this.pendingTransform = transform; } @Override public NewT get() { - if (held == null) { - return pendingActions.reduceAux(heldSrc.get(), - Function<T, T>::apply, f::apply); + if (heldValue == null) { + return pendingActions.reduceAux(heldSource.get(), + Function<T, T>::apply, pendingTransform::apply); } else { - return pendingActions.reduceAux(held, - Function<T, T>::apply, f::apply); + return pendingActions.reduceAux(heldValue, + Function<T, T>::apply, pendingTransform::apply); } } } @@ -50,76 +50,78 @@ public class LazyHolder<T> implements IHolder<T> { /** * List of queued actions to be performed on realized values */ - private FunctionalList<Function<T, T>> actions; + private FunctionalList<Function<T, T>> actions = + new FunctionalList<>(); /** * The value internally held by this lazy holder */ - private T held; + private T heldValue; /** * The source for a value held by this lazy holder */ - private Supplier<T> heldSrc; + private Supplier<T> heldSource; /** * Create a new lazy holder with the given supplier * - * @param src + * @param source * The supplier for a value when it is neededs */ - public LazyHolder(Supplier<T> src) { - heldSrc = src; + public LazyHolder(Supplier<T> source) { + heldSource = source; - held = null; + heldValue = null; } /** * Create a new lazy holder with the given value * - * @param val + * @param value * The value held in the holder */ - public LazyHolder(T val) { - held = val; + public LazyHolder(T value) { + heldValue = value; } @Override - public void doWith(Consumer<T> f) { - transform((val) -> { + public void doWith(Consumer<T> action) { + transform((value) -> { // Do the action with the value - f.accept(val); + action.accept(value); // Return the untransformed value - return val; + return value; }); } @Override - public <NewT> IHolder<NewT> map(Function<T, NewT> f) { + public <NewT> IHolder<NewT> map(Function<T, NewT> transform) { // Don't actually map until we need to - return new LazyHolder<>(new LazyHolderSupplier<>(actions, f)); + return new LazyHolder<>( + new LazyHolderSupplier<>(actions, transform)); } @Override - public IHolder<T> transform(Function<T, T> f) { + public IHolder<T> transform(Function<T, T> transform) { // Queue the transform until we need to apply it - actions.add(f); + actions.add(transform); return this; } @Override - public <E> E unwrap(Function<T, E> f) { + public <E> E unwrap(Function<T, E> unwrapper) { // Actualize ourselves - if (held == null) { - held = heldSrc.get(); + if (heldValue == null) { + heldValue = heldSource.get(); } // Apply all pending transforms - actions.forEach((act) -> held = act.apply(held)); + actions.forEach((action) -> heldValue = action.apply(heldValue)); - return f.apply(held); + return unwrapper.apply(heldValue); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyPair.java index 70b6f2f..3c21b56 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/lazy/LazyPair.java @@ -25,49 +25,51 @@ public class LazyPair<L, R> implements IPair<L, R> { /** * The backing store for this pair */ - protected IHolder<IPair<L, R>> del; + protected IHolder<IPair<L, R>> delegatePair; /** * Create a new blank lazy pair */ public LazyPair() { - del = new LazyHolder<>(new Pair<>()); + delegatePair = new LazyHolder<>(new Pair<>()); } /** * Create a new lazy pair with the specified initial values * - * @param leftVal + * @param leftValue * The initial value for the left side of the pair - * @param rightVal + * @param rightValue * The initial value for the right side of the pair */ - public LazyPair(L leftVal, R rightVal) { - del = new LazyHolder<>(new Pair<>(leftVal, rightVal)); + public LazyPair(L leftValue, R rightValue) { + delegatePair = new LazyHolder<>(new Pair<>(leftValue, rightValue)); } /** * Create a new lazy pair with the specified sources for initial values * - * @param leftValSrc + * @param leftValueSource * The function to call for the left initial value - * @param rightValSrc + * @param rightValueSource * The function to call for the right initial value */ - public LazyPair(Supplier<L> leftValSrc, Supplier<R> rightValSrc) { - del = new LazyHolder<>(() -> { - return new Pair<>(leftValSrc.get(), rightValSrc.get()); + public LazyPair(Supplier<L> leftValueSource, + Supplier<R> rightValueSource) { + delegatePair = new LazyHolder<>(() -> { + return new Pair<>(leftValueSource.get(), + rightValueSource.get()); }); } /** * Create a new lazy pair with a specified internal delegate * - * @param deleg + * @param delegate * The internal delegate for the pair */ - private LazyPair(IHolder<IPair<L, R>> deleg) { - del = deleg; + private LazyPair(IHolder<IPair<L, R>> delegate) { + delegatePair = delegate; } /* @@ -77,10 +79,10 @@ public class LazyPair<L, R> implements IPair<L, R> { * java.util.function.Function) */ @Override - public <L2, R2> IPair<L2, R2> apply(Function<L, L2> lf, - Function<R, R2> rf) { - IHolder<IPair<L2, R2>> newPair = - del.map(par -> par.apply(lf, rf)); + public <L2, R2> IPair<L2, R2> apply(Function<L, L2> leftTransform, + Function<R, R2> rightTransform) { + IHolder<IPair<L2, R2>> newPair = delegatePair + .map((currentPair) -> currentPair.apply(leftTransform, rightTransform)); return new LazyPair<>(newPair); } @@ -91,9 +93,9 @@ public class LazyPair<L, R> implements IPair<L, R> { * @see bjc.utils.data.IPair#doWith(java.util.function.BiConsumer) */ @Override - public void doWith(BiConsumer<L, R> bc) { - del.doWith((par) -> { - par.doWith(bc); + public void doWith(BiConsumer<L, R> action) { + delegatePair.doWith((currentPair) -> { + currentPair.doWith(action); }); } @@ -103,7 +105,7 @@ public class LazyPair<L, R> implements IPair<L, R> { * @see bjc.utils.data.IPair#merge(java.util.function.BiFunction) */ @Override - public <E> E merge(BiFunction<L, R, E> bf) { - return del.unwrap((par) -> par.merge(bf)); + public <E> E merge(BiFunction<L, R, E> merger) { + return delegatePair.unwrap((currentPair) -> currentPair.merge(merger)); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java index 681a702..50a2e60 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/FileNotChosenException.java @@ -9,9 +9,7 @@ import java.io.IOException; * */ public class FileNotChosenException extends IOException { - /** - * Version ID for serialization - */ + // Version ID for serialization private static final long serialVersionUID = -8753348705210831096L; /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java index 0967d9a..3d7187e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/PragmaFormatException.java @@ -14,10 +14,10 @@ public class PragmaFormatException extends InputMismatchException { /** * Create a new exception with the given message - * @param msg The message to explain why the exception was thrown + * @param message The message to explain why the exception was thrown */ - public PragmaFormatException(String msg) { - super(msg); + public PragmaFormatException(String message) { + super(message); } /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java index 54ae47d..6e2ef15 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java +++ b/BJC-Utils2/src/main/java/bjc/utils/exceptions/UnknownPragmaException.java @@ -9,19 +9,17 @@ import java.util.InputMismatchException; * */ public class UnknownPragmaException extends InputMismatchException { - /** - * Version id for serialization - */ + // Version ID for serialization private static final long serialVersionUID = -4277573484926638662L; /** * Create a new exception with the given cause * - * @param m + * @param cause * The cause for throwing this exception */ - public UnknownPragmaException(String m) { - super(m); + public UnknownPragmaException(String cause) { + super(cause); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java index aabd3cd..9652469 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java @@ -551,7 +551,7 @@ public class FunctionalList<E> implements Cloneable { StringBuilder sb = new StringBuilder("("); // Append the string form of each element - forEach(s -> sb.append(s + ", ")); + forEach(strang -> sb.append(strang + ", ")); // Remove trailing space and comma sb.deleteCharAt(sb.length() - 1); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java index d04510d..3c819cd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java @@ -55,11 +55,11 @@ public class FunctionalStringTokenizer { /** * Create a functional string tokenizer from a non-functional one * - * @param wrap + * @param toWrap * The non-functional string tokenizer to wrap */ - public FunctionalStringTokenizer(StringTokenizer wrap) { - this.input = wrap; + public FunctionalStringTokenizer(StringTokenizer toWrap) { + this.input = toWrap; } /** @@ -106,16 +106,16 @@ public class FunctionalStringTokenizer { * @param <E> * The type of the converted tokens * - * @param f + * @param tokenTransformer * The function to use to convert tokens. * @return A list containing all of the converted tokens. */ - public <E> FunctionalList<E> toList(Function<String, E> f) { + public <E> FunctionalList<E> toList(Function<String, E> tokenTransformer) { FunctionalList<E> returnList = new FunctionalList<>(); // Add each token to the list after transforming it - forEachToken(tk -> { - E transformedToken = f.apply(tk); + forEachToken(token -> { + E transformedToken = tokenTransformer.apply(token); returnList.add(transformedToken); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java index 2785626..ec0e4df 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java @@ -20,41 +20,42 @@ public class BinarySearchTree<T> { /** * The comparator for use in ordering items */ - private Comparator<T> comp; + private Comparator<T> comparator; /** * The current count of elements in the tree */ - private int nCount; + private int elementCount; /** * The root element of the tree */ - private ITreePart<T> root; + private ITreePart<T> rootElement; /** * Create a new tree using the specified way to compare elements. * * @param cmp + * The thing to use for comparing elements */ public BinarySearchTree(Comparator<T> cmp) { - nCount = 0; - comp = cmp; + elementCount = 0; + comparator = cmp; } /** * Add a node to the binary search tree. * - * @param dat + * @param element * The data to add to the binary search tree. */ - public void addNode(T dat) { - nCount++; + public void addNode(T element) { + elementCount++; - if (root == null) { - root = new BinarySearchTreeNode<>(dat, null, null); + if (rootElement == null) { + rootElement = new BinarySearchTreeNode<>(element, null, null); } else { - root.add(dat, comp); + rootElement.add(element, comparator); } } @@ -63,45 +64,79 @@ public class BinarySearchTree<T> { * time, but also O(N) space. */ public void balance() { - FunctionalList<T> elms = new FunctionalList<>(); + FunctionalList<T> elements = new FunctionalList<>(); - root.forEach(TreeLinearizationMethod.INORDER, e -> elms.add(e)); + // Add each element to the list in sorted order + rootElement.forEach(TreeLinearizationMethod.INORDER, + element -> elements.add(element)); - root = null; + // Clear the tree + rootElement = null; - int piv = elms.getSize() / 2; - int adj = 0; + // Set up the pivot and adjustment for readding elements + int pivot = elements.getSize() / 2; + int pivotAdjustment = 0; - while ((piv - adj) >= 0 && (piv + adj) < elms.getSize()) { - if (root == null) { - root = new BinarySearchTreeNode<>(elms.getByIndex(piv), - null, null); + // Add elements until there aren't any left + while (adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { + if (rootElement == null) { + // Create a new root element + rootElement = new BinarySearchTreeNode<>( + elements.getByIndex(pivot), null, null); } else { - root.add(elms.getByIndex(piv + adj), comp); - root.add(elms.getByIndex(piv - adj), comp); + // Add the left and right elements in a balanced manner + rootElement.add( + elements.getByIndex(pivot + pivotAdjustment), + comparator); + + rootElement.add( + elements.getByIndex(pivot - pivotAdjustment), + comparator); } - adj++; + // Increase the distance from the pivot + pivotAdjustment++; } - if ((piv - adj) >= 0) { - root.add(elms.getByIndex(piv - adj), comp); - } else if ((piv + adj) < elms.getSize()) { - root.add(elms.getByIndex(piv + adj), comp); + // Add any trailing unbalanced elements + if ((pivot - pivotAdjustment) >= 0) { + rootElement.add(elements.getByIndex(pivot - pivotAdjustment), + comparator); + } else if ((pivot + pivotAdjustment) < elements.getSize()) { + rootElement.add(elements.getByIndex(pivot + pivotAdjustment), + comparator); } } /** + * Check if an adjusted pivot falls with the bounds of a list + * + * @param elements + * The list to get bounds from + * @param pivot + * The pivot + * @param pivotAdjustment + * The distance from the pivot + * @return Whether the adjusted pivot is with the list + */ + private boolean adjustedPivotInBounds(FunctionalList<T> elements, + int pivot, int pivotAdjustment) { + return (pivot - pivotAdjustment) >= 0 + && (pivot + pivotAdjustment) < elements.getSize(); + } + + /** * Soft-delete a node from the tree. Soft-deleted nodes stay in the * tree until trim()/balance() is invoked, and are not included in * traversals/finds. * - * @param dat + * @param element + * The node to delete */ - public void deleteNode(T dat) { - nCount--; + public void deleteNode(T element) { + elementCount--; - root.delete(dat, comp); + rootElement.delete(element, comparator); } /** @@ -110,45 +145,49 @@ public class BinarySearchTree<T> { * @return The root of the tree. */ public ITreePart<T> getRoot() { - return root; + return rootElement; } /** * Check if a node is in the tree * - * @param dat + * @param element * The node to check the presence of for the tree. * @return Whether or not the node is in the tree. */ - public boolean isInTree(T dat) { - return root.contains(dat, comp); + public boolean isInTree(T element) { + return rootElement.contains(element, comparator); } /** * Traverse the tree in a specified way until the function fails * - * @param tlm + * @param linearizationMethod * The way to linearize the tree for traversal - * @param p + * @param traversalPredicate * The function to use until it fails */ - public void traverse(TreeLinearizationMethod tlm, Predicate<T> p) { - root.forEach(tlm, p); + public void traverse(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + rootElement.forEach(linearizationMethod, traversalPredicate); } /** * Remove all soft-deleted nodes from the tree. */ public void trim() { - List<T> nds = new ArrayList<>(nCount); + List<T> nodes = new ArrayList<>(elementCount); - traverse(TreeLinearizationMethod.PREORDER, d -> { - nds.add(d); + // Add all non-soft deleted nodes to the tree in insertion order + traverse(TreeLinearizationMethod.PREORDER, node -> { + nodes.add(node); return true; }); - root = null; + // Clear the tree + rootElement = null; - nds.forEach(d -> addNode(d)); + // Add the nodes to the tree in the order they were inserted + nodes.forEach(node -> addNode(node)); } -} +}
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java index 370e70c..7e31328 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java @@ -22,16 +22,16 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { /** * Whether this node is soft-deleted or not */ - protected boolean deleted; + protected boolean isDeleted; /** * Create a new leaf holding the specified data. * - * @param dat + * @param element * The data for the leaf to hold. */ - public BinarySearchTreeLeaf(T dat) { - data = dat; + public BinarySearchTreeLeaf(T element) { + data = element; } /* @@ -41,7 +41,7 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * java.util.Comparator) */ @Override - public void add(T dat, Comparator<T> comp) { + public void add(T element, Comparator<T> comparator) { throw new IllegalArgumentException("Can't add to a leaf."); } @@ -53,8 +53,9 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * java.util.function.BiFunction) */ @Override - public <E> E collapse(Function<T, E> f, BiFunction<E, E, E> bf) { - return f.apply(data); + public <E> E collapse(Function<T, E> leafTransformer, + BiFunction<E, E, E> branchCollapser) { + return leafTransformer.apply(data); } /* @@ -64,8 +65,8 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * java.util.Comparator) */ @Override - public boolean contains(T dat, Comparator<T> cmp) { - return this.data.equals(dat); + public boolean contains(T element, Comparator<T> comparator) { + return this.data.equals(element); } /* @@ -85,9 +86,9 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * java.util.Comparator) */ @Override - public void delete(T dat, Comparator<T> cmp) { - if (data.equals(dat)) { - deleted = true; + public void delete(T element, Comparator<T> comparator) { + if (data.equals(element)) { + isDeleted = true; } } @@ -99,8 +100,8 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * DirectedWalkFunction) */ @Override - public boolean directedWalk(DirectedWalkFunction<T> ds) { - switch (ds.walk(data)) { + public boolean directedWalk(DirectedWalkFunction<T> treeWalker) { + switch (treeWalker.walk(data)) { case SUCCESS: return true; default: @@ -116,7 +117,8 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { * TreeLinearizationMethod, java.util.function.Predicate) */ @Override - public boolean forEach(TreeLinearizationMethod tlm, Predicate<T> c) { - return c.test(data); + public boolean forEach(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + return traversalPredicate.test(data); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java index b51a9eb..77bb196 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java @@ -19,28 +19,28 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { /** * The left child of this node */ - private ITreePart<T> left; + private ITreePart<T> leftBranch; /** * The right child of this node */ - private ITreePart<T> right; + private ITreePart<T> rightBranch; /** * Create a new node with the specified data and children. * - * @param data + * @param element * The data to store in this node. * @param left * The left child of this node. * @param right * The right child of this node. */ - public BinarySearchTreeNode(T data, ITreePart<T> left, + public BinarySearchTreeNode(T element, ITreePart<T> left, ITreePart<T> right) { - super(data); - this.left = left; - this.right = right; + super(element); + this.leftBranch = left; + this.rightBranch = right; } /* @@ -50,58 +50,74 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { * java.util.Comparator) */ @Override - public void add(T dat, Comparator<T> comp) { - switch (comp.compare(data, dat)) { + public void add(T element, Comparator<T> comparator) { + switch (comparator.compare(data, element)) { case -1: - if (left == null) { - left = new BinarySearchTreeNode<>(dat, null, null); + if (leftBranch == null) { + leftBranch = new BinarySearchTreeNode<>(element, null, + null); } else { - left.add(dat, comp); + leftBranch.add(element, comparator); } case 0: - if (deleted) { - deleted = false; + if (isDeleted) { + isDeleted = false; } else { throw new IllegalArgumentException( "Can't add duplicate values"); } case 1: - if (right == null) { - right = new BinarySearchTreeNode<>(dat, null, null); + if (rightBranch == null) { + rightBranch = new BinarySearchTreeNode<>(element, null, + null); } else { - right.add(dat, comp); + rightBranch.add(element, comparator); } } } @Override - public <E> E collapse(Function<T, E> f, BiFunction<E, E, E> bf) { - E tm = f.apply(data); + public <E> E collapse(Function<T, E> nodeCollapser, + BiFunction<E, E, E> branchCollapser) { + E collapsedNode = nodeCollapser.apply(data); - if (left != null) { - if (right != null) { - return bf.apply(tm, bf.apply(left.collapse(f, bf), - right.collapse(f, bf))); + if (leftBranch != null) { + E collapsedLeftBranch = + leftBranch.collapse(nodeCollapser, branchCollapser); + if (rightBranch != null) { + E collapsedRightBranch = rightBranch + .collapse(nodeCollapser, branchCollapser); + + E collapsedBranches = branchCollapser + .apply(collapsedLeftBranch, collapsedRightBranch); + + return branchCollapser.apply(collapsedNode, + collapsedBranches); } else { - return bf.apply(tm, left.collapse(f, bf)); + return branchCollapser.apply(collapsedNode, + collapsedLeftBranch); } } else { - if (right != null) { - return bf.apply(tm, right.collapse(f, bf)); + if (rightBranch != null) { + E collapsedRightBranch = rightBranch + .collapse(nodeCollapser, branchCollapser); + + return branchCollapser.apply(collapsedNode, + collapsedRightBranch); } else { - return tm; + return collapsedNode; } } } @Override - public boolean contains(T dat, Comparator<T> cmp) { - return directedWalk(ds -> { - switch (cmp.compare(dat, ds)) { + public boolean contains(T element, Comparator<T> comparator) { + return directedWalk(currentElement -> { + switch (comparator.compare(element, currentElement)) { case -1: return LEFT; case 0: - return deleted ? FAILURE : SUCCESS; + return isDeleted ? FAILURE : SUCCESS; case 1: return RIGHT; default: @@ -111,16 +127,16 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public void delete(T dat, Comparator<T> cmp) { - directedWalk(ds -> { - switch (cmp.compare(data, dat)) { + public void delete(T element, Comparator<T> comparator) { + directedWalk(currentElement -> { + switch (comparator.compare(data, element)) { case -1: - return left == null ? FAILURE : LEFT; + return leftBranch == null ? FAILURE : LEFT; case 0: - deleted = true; + isDeleted = true; return FAILURE; case 1: - return right == null ? FAILURE : RIGHT; + return rightBranch == null ? FAILURE : RIGHT; default: return FAILURE; } @@ -128,14 +144,14 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public boolean directedWalk(DirectedWalkFunction<T> ds) { - switch (ds.walk(data)) { + public boolean directedWalk(DirectedWalkFunction<T> treeWalker) { + switch (treeWalker.walk(data)) { case SUCCESS: return true; case LEFT: - return left.directedWalk(ds); + return leftBranch.directedWalk(treeWalker); case RIGHT: - return right.directedWalk(ds); + return rightBranch.directedWalk(treeWalker); case FAILURE: return false; default: @@ -144,42 +160,119 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public boolean forEach(TreeLinearizationMethod tlm, Predicate<T> c) { - switch (tlm) { + public boolean forEach(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + switch (linearizationMethod) { case PREORDER: - return preorderTraverse(tlm, c); + return preorderTraverse(linearizationMethod, + traversalPredicate); case INORDER: - return inorderTraverse(tlm, c); + return inorderTraverse(linearizationMethod, + traversalPredicate); case POSTORDER: - return postorderTraverse(tlm, c); + return postorderTraverse(linearizationMethod, + traversalPredicate); default: throw new IllegalArgumentException( - "Passed an incorrect TreeLinearizationMethod."); + "Passed an incorrect TreeLinearizationMethod " + + linearizationMethod + ". WAT"); } } - private boolean inorderTraverse(TreeLinearizationMethod tlm, - Predicate<T> c) { + private boolean inorderTraverse( + TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { + return false; + } + + if (!traverseElement(traversalPredicate)) { + return false; + } + + if (!traverseRightBranch(linearizationMethod, + traversalPredicate)) { + return false; + } - return ((left == null ? true : left.forEach(tlm, c)) - && (deleted ? true : c.test(data)) - && (right == null ? true : right.forEach(tlm, c))); + return true; } - private boolean postorderTraverse(TreeLinearizationMethod tlm, - Predicate<T> c) { + private boolean postorderTraverse( + TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { - return ((left == null ? true : left.forEach(tlm, c)) - && (right == null ? true : right.forEach(tlm, c)) - && (deleted ? true : c.test(data))); + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { + return false; + } + + if (!traverseRightBranch(linearizationMethod, + traversalPredicate)) { + return false; + } + + if (!traverseElement(traversalPredicate)) { + return false; + } + + return true; } - private boolean preorderTraverse(TreeLinearizationMethod tlm, - Predicate<T> c) { + private boolean preorderTraverse( + TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + + if (!traverseElement(traversalPredicate)) { + return false; + } - return ((deleted ? true : c.test(data)) - && (left == null ? true : left.forEach(tlm, c)) - && (right == null ? true : right.forEach(tlm, c))); + if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { + return false; + } + + if (!traverseRightBranch(linearizationMethod, + traversalPredicate)) { + return false; + } + + return true; + } + + private boolean traverseElement(Predicate<T> traversalPredicate) { + boolean nodeSuccesfullyTraversed; + if (isDeleted) { + nodeSuccesfullyTraversed = true; + } else { + nodeSuccesfullyTraversed = traversalPredicate.test(data); + } + return nodeSuccesfullyTraversed; + } + + private boolean traverseLeftBranch( + TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + boolean leftSuccesfullyTraversed; + if (leftBranch == null) { + leftSuccesfullyTraversed = true; + } else { + leftSuccesfullyTraversed = leftBranch + .forEach(linearizationMethod, traversalPredicate); + } + return leftSuccesfullyTraversed; + } + + private boolean traverseRightBranch( + TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate) { + boolean rightSuccesfullyTraversed; + if (rightBranch == null) { + rightSuccesfullyTraversed = true; + } else { + rightSuccesfullyTraversed = rightBranch + .forEach(linearizationMethod, traversalPredicate); + } + return rightSuccesfullyTraversed; } -} +}
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java index 12c87b3..3f12fb6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/DirectedWalkFunction.java @@ -40,9 +40,9 @@ public interface DirectedWalkFunction<T> { /** * Perform a directed walk on a node of a tree. * - * @param data + * @param element * The data stored in the node currently being visited * @return The way the function wants the walk to go next. */ - public DirectedWalkResult walk(T data); + public DirectedWalkResult walk(T element); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java index 6ed9fa8..8fa5a3d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java @@ -41,13 +41,13 @@ public interface ITreePart<T> { /** * Add a element below this tree part somewhere. * - * @param dat + * @param element * The element to add below this tree part - * @param comp + * @param comparator * The thing to use for comparing values to find where to * insert the tree part. */ - public void add(T dat, Comparator<T> comp); + public void add(T element, Comparator<T> comparator); /** * Collapses this tree part into a single value. Does not change the @@ -56,26 +56,27 @@ public interface ITreePart<T> { * @param <E> * The type of the final collapsed value * - * @param f + * @param nodeCollapser * The function to use to transform data into mapped form. - * @param bf + * @param branchCollapser * The function to use to collapse data in mapped form into * a single value. * @return A single value from collapsing the tree. */ - public <E> E collapse(Function<T, E> f, BiFunction<E, E, E> bf); + public <E> E collapse(Function<T, E> nodeCollapser, + BiFunction<E, E, E> branchCollapser); /** * Check if this tre part or below it contains the specified data item * - * @param data + * @param element * The data item to look for. - * @param cmp + * @param comparator * The comparator to use to search for the data item * @return Whether or not the given item is contained in this tree part * or its children. */ - public boolean contains(T data, Comparator<T> cmp); + public boolean contains(T element, Comparator<T> comparator); /** * Get the data associated with this tree part. @@ -87,32 +88,33 @@ public interface ITreePart<T> { /** * Remove the given node from this tree part and any of its children. * - * @param dat + * @param element * The data item to remove. - * @param cmp + * @param comparator * The comparator to use to search for the data item. */ - public void delete(T dat, Comparator<T> cmp); + public void delete(T element, Comparator<T> comparator); /** * Execute a directed walk through the tree. * - * @param ds + * @param treeWalker * The function to use to direct the walk through the tree. * @return Whether the directed walk finished successfully. */ - public boolean directedWalk(DirectedWalkFunction<T> ds); + public boolean directedWalk(DirectedWalkFunction<T> treeWalker); /** * Execute a provided function for each element of tree it succesfully * completes for * - * @param tlm + * @param linearizationMethod * The way to linearize the tree for executing - * @param c + * @param traversalPredicate * The function to apply to each element, where it returning * false terminates traversal early * @return Whether the traversal finished succesfully */ - public boolean forEach(TreeLinearizationMethod tlm, Predicate<T> c); + public boolean forEach(TreeLinearizationMethod linearizationMethod, + Predicate<T> traversalPredicate); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java index 6e8c63a..3963e69 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -1,6 +1,7 @@ package bjc.utils.funcutils; import java.util.Deque; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; @@ -18,6 +19,74 @@ import bjc.utils.funcdata.FunctionalList; public class ListUtils { private static final int MAX_NTRIESPART = 50; + private static final class TokenDeaffixer + implements BiFunction<String, String, FunctionalList<String>> { + private String token; + + public TokenDeaffixer(String tok) { + token = tok; + } + + @Override + public FunctionalList<String> apply(String opName, + String opRegex) { + if (StringUtils.containsOnly(token, opRegex)) { + return new FunctionalList<>(token); + } else if (token.startsWith(opName)) { + return new FunctionalList<>(opName, + token.split(opRegex)[1]); + } else if (token.endsWith(opName)) { + return new FunctionalList<>(token.split(opRegex)[0], + opName); + } else { + return new FunctionalList<>(token); + } + } + } + + private static final class TokenSplitter + implements BiFunction<String, String, FunctionalList<String>> { + private String tokenToSplit; + + public TokenSplitter(String tok) { + this.tokenToSplit = tok; + } + + @Override + public FunctionalList<String> apply(String operatorName, + String operatorRegex) { + if (tokenToSplit.contains(operatorName)) { + if (StringUtils.containsOnly(tokenToSplit, + operatorRegex)) { + return new FunctionalList<>(tokenToSplit); + } else { + FunctionalList<String> splitTokens = + new FunctionalList<>( + tokenToSplit.split(operatorRegex)); + + FunctionalList<String> result = new FunctionalList<>(); + + int tokenExpansionSize = splitTokens.getSize(); + + splitTokens.forEachIndexed((tokenIndex, token) -> { + + if (tokenIndex != tokenExpansionSize + && tokenIndex != 0) { + result.add(operatorName); + result.add(token); + } else { + result.add(token); + } + }); + + return result; + } + } else { + return new FunctionalList<>(tokenToSplit); + } + } + } + /** * Implements a single group partitioning pass on a list * @@ -28,42 +97,48 @@ public class ListUtils { */ private static final class GroupPartIteration<E> implements Consumer<E> { - private FunctionalList<FunctionalList<E>> ret; - private GenHolder<FunctionalList<E>> currPart; - private FunctionalList<E> rejects; - private GenHolder<Integer> numInCurrPart; - private int nPerPart; - private Function<E, Integer> eleCount; - - public GroupPartIteration(FunctionalList<FunctionalList<E>> ret, + private FunctionalList<FunctionalList<E>> returnedList; + private GenHolder<FunctionalList<E>> currentPartition; + private FunctionalList<E> rejectedItems; + private GenHolder<Integer> numberInCurrentPartition; + private int numberPerPartition; + private Function<E, Integer> elementCounter; + + public GroupPartIteration( + FunctionalList<FunctionalList<E>> returned, GenHolder<FunctionalList<E>> currPart, FunctionalList<E> rejects, GenHolder<Integer> numInCurrPart, int nPerPart, Function<E, Integer> eleCount) { - this.ret = ret; - this.currPart = currPart; - this.rejects = rejects; - this.numInCurrPart = numInCurrPart; - this.nPerPart = nPerPart; - this.eleCount = eleCount; + this.returnedList = returned; + this.currentPartition = currPart; + this.rejectedItems = rejects; + this.numberInCurrentPartition = numInCurrPart; + this.numberPerPartition = nPerPart; + this.elementCounter = eleCount; } @Override - public void accept(E val) { - if (numInCurrPart.unwrap((vl) -> vl >= nPerPart)) { - ret.add(currPart.unwrap((vl) -> vl)); + public void accept(E value) { + if (numberInCurrentPartition + .unwrap((number) -> number >= numberPerPartition)) { + returnedList.add( + currentPartition.unwrap((partition) -> partition)); - currPart.transform((vl) -> new FunctionalList<>()); - numInCurrPart.transform((vl) -> 0); + currentPartition + .transform((partition) -> new FunctionalList<>()); + numberInCurrentPartition.transform((number) -> 0); } else { - int vCount = eleCount.apply(val); + int currentElementCount = elementCounter.apply(value); - if (numInCurrPart - .unwrap((vl) -> (vl + vCount) >= nPerPart)) { - rejects.add(val); + if (numberInCurrentPartition.unwrap((number) -> (number + + currentElementCount) >= numberPerPartition)) { + rejectedItems.add(value); } else { - currPart.unwrap((vl) -> vl.add(val)); - numInCurrPart.transform((vl) -> vl + vCount); + currentPartition + .unwrap((partition) -> partition.add(value)); + numberInCurrentPartition.transform( + (number) -> number + currentElementCount); } } } @@ -76,59 +151,66 @@ public class ListUtils { * @param <E> * The type of elements in the list to partition * - * @param list + * @param input * The list to partition - * @param eleCount + * @param elementCounter * The function to determine the count for each element for - * @param nPerPart + * @param numberPerPartition * The number of elements to put in each partition * @return A list partitioned according to the above rules */ public static <E> FunctionalList<FunctionalList<E>> groupPartition( - FunctionalList<E> list, Function<E, Integer> eleCount, - int nPerPart) { + FunctionalList<E> input, Function<E, Integer> elementCounter, + int numberPerPartition) { /* * List that holds our results */ - FunctionalList<FunctionalList<E>> ret = new FunctionalList<>(); + FunctionalList<FunctionalList<E>> returnedList = + new FunctionalList<>(); /* * List that holds current partition */ - GenHolder<FunctionalList<E>> currPart = + GenHolder<FunctionalList<E>> currentPartition = new GenHolder<>(new FunctionalList<>()); /* * List that holds elements rejected during current pass */ - FunctionalList<E> rejects = new FunctionalList<>(); + FunctionalList<E> rejectedElements = new FunctionalList<>(); /* * The effective number of elements in the current partitition */ - GenHolder<Integer> numInCurrPart = new GenHolder<>(0); + GenHolder<Integer> numberInCurrentPartition = new GenHolder<>(0); /* * Run up to a certain number of passes */ - for (int nIterations = 0; nIterations < MAX_NTRIESPART - && !rejects.isEmpty(); nIterations++) { - list.forEach(new GroupPartIteration<>(ret, currPart, rejects, - numInCurrPart, nPerPart, eleCount)); + for (int numberOfIterations = + 0; numberOfIterations < MAX_NTRIESPART + && !rejectedElements + .isEmpty(); numberOfIterations++) { + input.forEach(new GroupPartIteration<>(returnedList, + currentPartition, rejectedElements, + numberInCurrentPartition, numberPerPartition, + elementCounter)); - if (rejects.isEmpty()) { + if (rejectedElements.isEmpty()) { // Nothing was rejected, so we're done - return ret; + return returnedList; } } - throw new IllegalArgumentException("Heuristic (more than " - + MAX_NTRIESPART - + " iterations of partitioning) detected unpartitionable list " - + list.toString() - + "\nThe following elements were not partitioned: " - + rejects.toString() + "\nCurrent group in formation: " - + currPart.unwrap((vl) -> vl.toString()) - + "\nPreviously formed groups: " + ret.toString()); + throw new IllegalArgumentException( + "Heuristic (more than " + MAX_NTRIESPART + + " iterations of partitioning) detected unpartitionable list " + + input.toString() + + "\nThe following elements were not partitioned: " + + rejectedElements.toString() + + "\nCurrent group in formation: " + + currentPartition.unwrap((vl) -> vl.toString()) + + "\nPreviously formed groups: " + + returnedList.toString()); } /** @@ -139,49 +221,23 @@ public class ListUtils { * * @param input * The tokens to split - * @param ops - * The operators to split on. + * @param operators + * Pairs of operators to split on and regexes that match + * those operators * @return A list of tokens split on all the operators * */ public static FunctionalList<String> splitTokens( FunctionalList<String> input, - Deque<Pair<String, String>> ops) { + Deque<Pair<String, String>> operators) { GenHolder<FunctionalList<String>> ret = new GenHolder<>(input); - ops.forEach( + operators.forEach( (op) -> ret.transform((oldRet) -> oldRet.flatMap((tok) -> { - return op.merge((opName, opRegex) -> { - if (tok.contains(opName)) { - if (StringUtils.containsOnly(tok, opRegex)) { - return new FunctionalList<>(tok); - } else { - FunctionalList<String> splitTokens = - new FunctionalList<>( - tok.split(opRegex)); - FunctionalList<String> rt = - new FunctionalList<>(); - int tkSize = splitTokens.getSize(); - splitTokens.forEachIndexed((idx, tk) -> { - - if (idx != tkSize && idx != 0) { - rt.add(opName); - rt.add(tk); - - } else { - rt.add(tk); - - } - }); - return rt; - } - } else { - return new FunctionalList<>(tok); - } - }); + return op.merge(new TokenSplitter(tok)); }))); - return ret.unwrap((l) -> l); + return ret.unwrap((list) -> list); } /** @@ -194,32 +250,18 @@ public class ListUtils { * @return The tokens that have been deaffixed * */ - @SuppressWarnings("unchecked") public static FunctionalList<String> deAffixTokens( FunctionalList<String> input, Deque<Pair<String, String>> ops) { - GenHolder<FunctionalList<String>> ret = new GenHolder<>(input); + GenHolder<FunctionalList<String>> returnedList = + new GenHolder<>(input); - ops.forEach( - (op) -> ret.transform((oldRet) -> oldRet.flatMap((tok) -> { - return (FunctionalList<String>) op - .merge((opName, opRegex) -> { - if (StringUtils.containsOnly(tok, - opRegex)) { - return new FunctionalList<>(tok); - } else if (tok.startsWith(opName)) { - return new FunctionalList<>(op, - tok.split(opRegex)[1]); - } else if (tok.endsWith(opName)) { - return new FunctionalList<>( - tok.split(opRegex)[0], op); - } else { - return new FunctionalList<>(tok); - } - }); + ops.forEach((op) -> returnedList + .transform((oldRet) -> oldRet.flatMap((tok) -> { + return op.merge(new TokenDeaffixer(tok)); }))); - return ret.unwrap((l) -> l); + return returnedList.unwrap((list) -> list); } /** @@ -232,6 +274,7 @@ public class ListUtils { */ public static String collapseTokens(FunctionalList<String> input) { return input.reduceAux("", - (currString, state) -> state + currString, (s) -> s); + (currentString, state) -> state + currentString, + (strang) -> strang); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StatementUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StatementUtils.java deleted file mode 100644 index 9b4b03f..0000000 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StatementUtils.java +++ /dev/null @@ -1,11 +0,0 @@ -package bjc.utils.funcutils; - -/** - * Contains methods that produce effects mimicking statements - * - * @author ben - * - */ -public class StatementUtils { - -} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java index 339b3f4..ca0578d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/RandomGrammar.java @@ -31,8 +31,8 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { */ @SafeVarargs public final void addCases(E rule, FunctionalList<E>... cases) { - for (FunctionalList<E> cse : cases) { - super.addCase(rule, 1, cse); + for (FunctionalList<E> currentCase : cases) { + super.addCase(rule, 1, currentCase); } } @@ -48,8 +48,8 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { public final void makeRule(E rule, FunctionalList<E>... cases) { super.addRule(rule); - for (FunctionalList<E> cse : cases) { - super.addCase(rule, 1, cse); + for (FunctionalList<E> currentCase : cases) { + super.addCase(rule, 1, currentCase); } } @@ -64,6 +64,6 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { public void makeRule(E rule, FunctionalList<FunctionalList<E>> cases) { super.addRule(rule); - cases.forEach(cse -> super.addCase(rule, 1, cse)); + cases.forEach(currentCase -> super.addCase(rule, 1, currentCase)); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java index 463ad8b..28b61c5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedGrammar.java @@ -22,7 +22,7 @@ public class WeightedGrammar<E> { /** * The initial rule of the grammar */ - protected String initRule; + protected String initialRule; /** * The rules currently in this grammar @@ -32,7 +32,7 @@ public class WeightedGrammar<E> { /** * The random number generator used for random numbers */ - private Random sr; + private Random rng; /** * All of the subgrammars of this grammar @@ -51,13 +51,13 @@ public class WeightedGrammar<E> { * Create a new weighted grammar that uses the specified source of * randomness. * - * @param src + * @param source * The source of randomness to use */ - public WeightedGrammar(Random src) { + public WeightedGrammar(Random source) { this(); - sr = src; + rng = source; } /** @@ -65,13 +65,13 @@ public class WeightedGrammar<E> { * * @param rule * The rule to add a case to. - * @param prob + * @param probability * The probability for this rule to be chosen. * @param cse * The case being added. */ - public void addCase(E rule, int prob, FunctionalList<E> cse) { - rules.get(rule).addProb(prob, cse); + public void addCase(E rule, int probability, FunctionalList<E> cse) { + rules.get(rule).addProbability(probability, cse); } /** @@ -104,10 +104,10 @@ public class WeightedGrammar<E> { * @return Whether or not the rule was succesfully added. */ public boolean addRule(E name) { - if (sr == null) { - sr = new Random(); + if (rng == null) { + rng = new Random(); } - return addRule(name, new WeightedRandom<>(sr)); + return addRule(name, new WeightedRandom<>(rng)); } /** @@ -115,15 +115,16 @@ public class WeightedGrammar<E> { * * @param name * The name of the rule to add. - * @param rnd + * @param cases * The set of cases for the rule. * @return Whether or not the rule was succesfully added. */ - public boolean addRule(E name, WeightedRandom<FunctionalList<E>> rnd) { + public boolean addRule(E name, + WeightedRandom<FunctionalList<E>> cases) { if (rules.containsKey(name)) { return false; } else { - rules.put(name, rnd); + rules.put(name, cases); return true; } } @@ -133,15 +134,15 @@ public class WeightedGrammar<E> { * * @param name * The name of the subgrammar. - * @param subG + * @param subgrammar * The subgrammar to add. * @return Whether or not the subgrammar was succesfully added. */ - public boolean addSubGrammar(E name, WeightedGrammar<E> subG) { + public boolean addSubgrammar(E name, WeightedGrammar<E> subgrammar) { if (subgrammars.containsKey(name)) { return false; } else { - subgrammars.put(name, subG); + subgrammars.put(name, subgrammar); return true; } } @@ -150,20 +151,23 @@ public class WeightedGrammar<E> { * Generate a set of debug sentences for the specified rule. Only * generates sentances one layer deep. * - * @param rl + * @param ruleName * The rule to test. * @return A set of sentances generated by the specified rule. */ - public FunctionalList<FunctionalList<E>> debugVals(E rl) { - FunctionalList<FunctionalList<E>> fl = new FunctionalList<>(); + public FunctionalList<FunctionalList<E>> + generateDebugValues(E ruleName) { + FunctionalList<FunctionalList<E>> returnedList = + new FunctionalList<>(); - WeightedRandom<FunctionalList<E>> random = rules.get(rl); + WeightedRandom<FunctionalList<E>> ruleGenerator = + rules.get(ruleName); for (int i = 0; i < 10; i++) { - fl.add(random.genVal()); + returnedList.add(ruleGenerator.generateValue()); } - return fl; + return returnedList; } /** @@ -172,52 +176,55 @@ public class WeightedGrammar<E> { * @param <T> * The type of the transformed output * - * @param initRle + * @param initRule * The initial rule to start with. - * @param f + * @param tokenTransformer * The function to transform grammar output into something. * @param spacer * The spacer element to add in between output tokens. * @return A randomly generated sentance from the specified initial * rule. */ - public <T> FunctionalList<T> genGeneric(E initRle, Function<E, T> f, - T spacer) { - FunctionalList<T> r = new FunctionalList<>(); - - if (subgrammars.containsKey(initRle)) { - subgrammars.get(initRle).genGeneric(initRle, f, spacer) - .forEach(rp -> { - r.add(rp); - r.add(spacer); + public <T> FunctionalList<T> generateGenericValues(E initRule, + Function<E, T> tokenTransformer, T spacer) { + FunctionalList<T> returnedList = new FunctionalList<>(); + + if (subgrammars.containsKey(initRule)) { + subgrammars.get(initRule).generateGenericValues(initRule, + tokenTransformer, spacer).forEach(rulePart -> { + returnedList.add(rulePart); + returnedList.add(spacer); }); - } else if (rules.containsKey(initRle)) { - rules.get(initRle).genVal().forEach( - rp -> genGeneric(rp, f, spacer).forEach(rp2 -> { - r.add(rp2); - r.add(spacer); - })); + } else if (rules.containsKey(initRule)) { + rules.get(initRule).generateValue() + .forEach(rulePart -> generateGenericValues(rulePart, + tokenTransformer, spacer) + .forEach(generatedRulePart -> { + returnedList + .add(generatedRulePart); + returnedList.add(spacer); + })); } else { - r.add(f.apply(initRle)); - r.add(spacer); + returnedList.add(tokenTransformer.apply(initRule)); + returnedList.add(spacer); } - return r; + return returnedList; } /** * Generate a random list of grammar elements from a given initial * rule. * - * @param initRle + * @param initRule * The initial rule to start with. * @param spacer * The item to use to space the list. * @return A list of random grammar elements generated by the specified * rule. */ - public FunctionalList<E> genList(E initRle, E spacer) { - return genGeneric(initRle, s -> s, spacer); + public FunctionalList<E> generateListValues(E initRule, E spacer) { + return generateGenericValues(initRule, strang -> strang, spacer); } /** @@ -225,8 +232,8 @@ public class WeightedGrammar<E> { * * @return The initial rule of this grammar */ - public String getInitRule() { - return initRule; + public String getInitialRule() { + return initialRule; } /** @@ -236,7 +243,7 @@ public class WeightedGrammar<E> { * The name of the subgrammar to get. * @return The subgrammar with the specified name. */ - public WeightedGrammar<E> getSubGrammar(E name) { + public WeightedGrammar<E> getSubgrammar(E name) { return subgrammars.get(name); } @@ -245,80 +252,85 @@ public class WeightedGrammar<E> { * * @return Whether or not this grammar has an initial rule */ - public boolean hasInitRule() { - return initRule != null && !initRule.equalsIgnoreCase(""); + public boolean hasInitialRule() { + return initialRule != null && !initialRule.equalsIgnoreCase(""); } /** * Prefix a given rule with a token multiple times * - * @param rName + * @param ruleName * The name of the rule to prefix * @param prefixToken * The token to prefix to the rules - * @param addProb + * @param additionalProbability * The additional probability of the tokens - * @param nTimes + * @param numberOfTimes * The number of times to prefix the token */ - public void multiPrefixRule(E rName, E prefixToken, int addProb, - int nTimes) { - WeightedRandom<FunctionalList<E>> rule = rules.get(rName); + public void multiPrefixRule(E ruleName, E prefixToken, + int additionalProbability, int numberOfTimes) { + WeightedRandom<FunctionalList<E>> rule = rules.get(ruleName); FunctionalList<Pair<Integer, FunctionalList<E>>> newResults = new FunctionalList<>(); - rule.getValues().forEach((par) -> { - FunctionalList<FunctionalList<E>> nls = new FunctionalList<>(); + rule.getValues().forEach((pair) -> { + FunctionalList<FunctionalList<E>> newRule = + new FunctionalList<>(); - // TODO bugtest this. if it works, write multiSuffixWith - for (int i = 1; i <= nTimes; i++) { - FunctionalList<E> nl = - par.merge((left, right) -> right.clone()); + for (int i = 1; i <= numberOfTimes; i++) { + FunctionalList<E> newCase = + pair.merge((left, right) -> right.clone()); for (int j = 1; j <= i; j++) { - nl.prepend(prefixToken); + newCase.prepend(prefixToken); } - nls.add(nl); + newRule.add(newCase); } - nls.forEach((ls) -> newResults.add(new Pair<>( - par.merge((left, right) -> left) + addProb, ls))); + newRule.forEach( + (list) -> newResults + .add(new Pair<>( + pair.merge((left, right) -> left) + + additionalProbability, + list))); }); - newResults.forEach((par) -> par - .doWith((left, right) -> addCase(rName, left, right))); + newResults.forEach((pair) -> pair + .doWith((left, right) -> addCase(ruleName, left, right))); } /** * Create a series of alternatives for a rule by prefixing them with a * given token * - * @param addProb + * @param additionalProbability * The amount to adjust the probability by - * @param rName + * @param ruleName * The name of the rule to prefix * @param prefixToken * The token to prefix to the rule */ - public void prefixRule(E rName, E prefixToken, int addProb) { - WeightedRandom<FunctionalList<E>> rule = rules.get(rName); + public void prefixRule(E ruleName, E prefixToken, + int additionalProbability) { + WeightedRandom<FunctionalList<E>> rule = rules.get(ruleName); FunctionalList<Pair<Integer, FunctionalList<E>>> newResults = new FunctionalList<>(); - rule.getValues().forEach((par) -> { - FunctionalList<E> nl = - par.merge((left, right) -> right.clone()); - nl.prepend(prefixToken); + rule.getValues().forEach((pair) -> { + FunctionalList<E> newCase = + pair.merge((left, right) -> right.clone()); + newCase.prepend(prefixToken); - newResults.add(new Pair<>( - par.merge((left, right) -> left) + addProb, nl)); + newResults.add(new Pair<>(pair.merge((left, right) -> left) + + additionalProbability, newCase)); }); - newResults.forEach((par) -> par - .doWith((left, right) -> addCase(rName, left, right))); + newResults.forEach((pair) -> pair + .doWith((left, right) -> addCase(ruleName, left, right))); } /** @@ -327,7 +339,7 @@ public class WeightedGrammar<E> { * @param name * The name of the rule to remove. */ - public void removeRule(E name) { + public void deleteRule(E name) { rules.remove(name); } @@ -337,7 +349,7 @@ public class WeightedGrammar<E> { * @param name * The name of the subgrammar to remove. */ - public void removeSubgrammar(E name) { + public void deleteSubgrammar(E name) { subgrammars.remove(name); } @@ -346,7 +358,7 @@ public class WeightedGrammar<E> { * * @return The number of rules in this grammar */ - public int ruleCount() { + public int getRuleCount() { return rules.size(); } @@ -355,7 +367,7 @@ public class WeightedGrammar<E> { * * @return The set of all rule names in this grammar */ - public Set<E> ruleNames() { + public Set<E> getRuleNames() { return rules.keySet(); } @@ -363,37 +375,39 @@ public class WeightedGrammar<E> { * Set the initial rule of the graphic * * @param initRule + * The initial rule of this grammar */ - public void setInitRule(String initRule) { - this.initRule = initRule; + public void setInitialRule(String initRule) { + this.initialRule = initRule; } /** * Suffix a token to a rule * - * @param rName + * @param ruleName * The rule to suffix * @param prefixToken * The token to prefix to the rule - * @param addProb + * @param additionalProbability * Additional probability of the prefixed rule */ - public void suffixRule(E rName, E prefixToken, int addProb) { - WeightedRandom<FunctionalList<E>> rule = rules.get(rName); + public void suffixRule(E ruleName, E prefixToken, + int additionalProbability) { + WeightedRandom<FunctionalList<E>> rule = rules.get(ruleName); FunctionalList<Pair<Integer, FunctionalList<E>>> newResults = new FunctionalList<>(); rule.getValues().forEach((par) -> { - FunctionalList<E> nl = + FunctionalList<E> newCase = par.merge((left, right) -> right.clone()); - nl.add(prefixToken); + newCase.add(prefixToken); - newResults.add(new Pair<>( - par.merge((left, right) -> left) + addProb, nl)); + newResults.add(new Pair<>(par.merge((left, right) -> left) + + additionalProbability, newCase)); }); - newResults.forEach((par) -> par - .doWith((left, right) -> addCase(rName, left, right))); + newResults.forEach((pair) -> pair + .doWith((left, right) -> addCase(ruleName, left, right))); } -} +}
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java index 3ddb8ef..5a8ef8f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -19,7 +19,7 @@ public class WeightedRandom<E> { /** * The list of probabilities for each result */ - private FunctionalList<Integer> probs; + private FunctionalList<Integer> probabilities; /** * The list of possible results to pick from @@ -29,7 +29,7 @@ public class WeightedRandom<E> { /** * The source for any needed random numbers */ - private Random src; + private Random source; private int totalChance; @@ -37,14 +37,14 @@ public class WeightedRandom<E> { * Create a new weighted random generator with the specified source of * randomness * - * @param sr + * @param src * The source of randomness to use. */ - public WeightedRandom(Random sr) { - probs = new FunctionalList<>(); + public WeightedRandom(Random src) { + probabilities = new FunctionalList<>(); results = new FunctionalList<>(); - src = sr; + source = src; } /** @@ -52,12 +52,12 @@ public class WeightedRandom<E> { * * @param chance * The chance to get this result. - * @param res + * @param result * The result to get when the chance comes up. */ - public void addProb(int chance, E res) { - probs.add(chance); - results.add(res); + public void addProbability(int chance, E result) { + probabilities.add(chance); + results.add(result); totalChance += chance; } @@ -67,24 +67,28 @@ public class WeightedRandom<E> { * * @return A random value selected in a weighted fashion. */ - public E genVal() { - GenHolder<Integer> v = new GenHolder<>(src.nextInt(totalChance)); - IHolder<E> res = new GenHolder<>(); - GenHolder<Boolean> bl = new GenHolder<>(true); + public E generateValue() { + GenHolder<Integer> randomValue = + new GenHolder<>(source.nextInt(totalChance)); + IHolder<E> currentResult = new GenHolder<>(); + GenHolder<Boolean> valuePicked = new GenHolder<>(true); - probs.forEachIndexed((i, p) -> { - if (bl.unwrap(vl -> vl)) { - if (v.unwrap((vl) -> vl < p)) { - res.transform((vl) -> results.getByIndex(i)); + probabilities.forEachIndexed((itemIndex, itemProbability) -> { + if (valuePicked.unwrap(bool -> bool)) { + if (randomValue + .unwrap((number) -> number < itemProbability)) { + currentResult.transform( + (result) -> results.getByIndex(itemIndex)); - bl.transform((vl) -> false); + valuePicked.transform((bool) -> false); } else { - v.transform((vl) -> vl - p); + randomValue.transform( + (number) -> number - itemProbability); } } }); - return res.unwrap((vl) -> vl); + return currentResult.unwrap((result) -> result); } /** @@ -103,6 +107,6 @@ public class WeightedRandom<E> { * @return A list of pairs of values and value probabilities */ public FunctionalList<Pair<Integer, E>> getValues() { - return probs.pairWith(results); + return probabilities.pairWith(results); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java index 6420d8e..513044e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -6,6 +6,7 @@ import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.stream.IntStream; @@ -29,43 +30,44 @@ public class AdjacencyMap<T> { * @return An adjacency map defined by the text */ public static AdjacencyMap<Integer> fromStream(InputStream stream) { - Scanner scn = new Scanner(stream); - scn.useDelimiter("\n"); + Scanner inputSource = new Scanner(stream); + inputSource.useDelimiter("\n"); // First, read in number of vertices - int numVertices = Integer.parseInt(scn.next()); + int numVertices = Integer.parseInt(inputSource.next()); Set<Integer> vertices = new HashSet<>(); - IntStream.range(0, numVertices).forEach(e -> vertices.add(e)); + IntStream.range(0, numVertices) + .forEach(element -> vertices.add(element)); // Create the adjacency map - AdjacencyMap<Integer> aMap = new AdjacencyMap<>(vertices); + AdjacencyMap<Integer> adjacencyMap = new AdjacencyMap<>(vertices); GenHolder<Integer> row = new GenHolder<>(0); - scn.forEachRemaining((strang) -> { + inputSource.forEachRemaining((strang) -> { String[] parts = strang.split(" "); - int col = 0; + int column = 0; for (String part : parts) { - aMap.setWeight(row.unwrap(vl -> vl), col, - Integer.parseInt(part)); + adjacencyMap.setWeight(row.unwrap(number -> number), + column, Integer.parseInt(part)); - col++; + column++; } - row.transform((vl) -> vl + 1); + row.transform((number) -> number + 1); }); - scn.close(); + inputSource.close(); - return aMap; + return adjacencyMap; } /** * The backing storage of the map */ - private Map<T, Map<T, Integer>> adjMap; + private Map<T, Map<T, Integer>> adjacencyMap = new HashMap<>(); /** * Create a new map from a set of vertices @@ -74,12 +76,13 @@ public class AdjacencyMap<T> { * The set of vertices to create a map from */ public AdjacencyMap(Set<T> vertices) { - vertices.forEach(src -> { - Map<T, Integer> srcRow = new HashMap<>(); + vertices.forEach(vertex -> { + Map<T, Integer> vertexRow = new HashMap<>(); - vertices.forEach(tgt -> srcRow.put(tgt, 0)); + vertices.forEach( + targetVertex -> vertexRow.put(targetVertex, 0)); - adjMap.put(src, srcRow); + adjacencyMap.put(vertex, vertexRow); }); } @@ -89,33 +92,37 @@ public class AdjacencyMap<T> { * @return Whether or not the graph is directed */ public boolean isDirected() { - GenHolder<Boolean> res = new GenHolder<>(true); - - adjMap.entrySet() - .forEach(src -> src.getValue().entrySet().forEach(tgt -> { - int lhs = tgt.getValue(); - int rhs = adjMap.get(tgt.getKey()).get(src.getKey()); - - if (lhs != rhs) { - res.transform((vl) -> false); - } - })); + GenHolder<Boolean> result = new GenHolder<>(true); + + adjacencyMap.entrySet().forEach(mapEntry -> { + Set<Entry<T, Integer>> entryVertices = + mapEntry.getValue().entrySet(); + entryVertices.forEach(targetVertex -> { + int leftValue = targetVertex.getValue(); + int rightValue = adjacencyMap.get(targetVertex.getKey()) + .get(mapEntry.getKey()); + + if (leftValue != rightValue) { + result.transform((bool) -> false); + } + }); + }); - return res.unwrap(vl -> vl); + return result.unwrap(bool -> bool); } /** * Set the weight of an edge * - * @param src + * @param sourceVertex * The source node of the edge - * @param tgt + * @param targetVertex * The target node of the edge - * @param weight + * @param edgeWeight * The weight of the edge */ - public void setWeight(T src, T tgt, int weight) { - adjMap.get(src).put(tgt, weight); + public void setWeight(T sourceVertex, T targetVertex, int edgeWeight) { + adjacencyMap.get(sourceVertex).put(targetVertex, edgeWeight); } /** @@ -124,31 +131,33 @@ public class AdjacencyMap<T> { * @return The new representation of this graph */ public Graph<T> toGraph() { - Graph<T> ret = new Graph<>(); + Graph<T> returnedGraph = new Graph<>(); - adjMap.entrySet() - .forEach(src -> src.getValue().entrySet() - .forEach(tgt -> ret.addEdge(src.getKey(), - tgt.getKey(), tgt.getValue()))); + adjacencyMap.entrySet().forEach(sourceVertex -> sourceVertex + .getValue().entrySet() + .forEach(targetVertex -> returnedGraph.addEdge( + sourceVertex.getKey(), targetVertex.getKey(), + targetVertex.getValue()))); - return ret; + return returnedGraph; } /** * Convert an adjacency map back into a stream * - * @param os + * @param outputSource * The stream to convert to */ - public void toStream(OutputStream os) { - PrintStream ps = new PrintStream(os); - - adjMap.entrySet().forEach(src -> { - src.getValue().entrySet() - .forEach(tgt -> ps.printf("%d ", tgt.getValue())); - ps.println(); + public void toStream(OutputStream outputSource) { + PrintStream outputPrinter = new PrintStream(outputSource); + + adjacencyMap.entrySet().forEach(sourceVertex -> { + sourceVertex.getValue().entrySet() + .forEach(targetVertex -> outputPrinter.printf("%d ", + targetVertex.getValue())); + outputPrinter.println(); }); - ps.close(); + outputPrinter.close(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java index cf0764b..44aa8e7 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java @@ -22,16 +22,16 @@ public class Edge<T> { /** * Create a new edge with set parameters * - * @param node1 + * @param initialNode * The initial node of the edge - * @param node2 + * @param terminalNode * The terminal node of the edge * @param distance * The distance between initial and terminal edge */ - public Edge(T node1, T node2, int distance) { - this.source = node1; - this.target = node2; + public Edge(T initialNode, T terminalNode, int distance) { + this.source = initialNode; + this.target = terminalNode; this.distance = distance; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java index d7aff34..5172df5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java @@ -29,44 +29,47 @@ public class Graph<T> { /** * The backing representation of the graph */ - private final Map<T, Map<T, Integer>> graph; + private final Map<T, Map<T, Integer>> backingGraph; /** * Create a new graph */ public Graph() { - graph = new HashMap<>(); + backingGraph = new HashMap<>(); } /** * Add a edge to the graph * - * @param source + * @param sourceVertex * The source vertex for this edge - * @param target + * @param targetVertex * The target vertex for this edge * @param distance * The distance from the source vertex to the target vertex */ - public void addEdge(T source, T target, int distance) { + public void addEdge(T sourceVertex, T targetVertex, int distance) { // Can't add edges with a null source or target - if (source == null) { - throw new NullPointerException("The vertex 1 cannot be null"); + if (sourceVertex == null) { + throw new NullPointerException( + "The source vertex cannot be null"); } - if (target == null) { - throw new NullPointerException("The vertex 2 cannot be null"); + + if (targetVertex == null) { + throw new NullPointerException( + "The target vertex cannot be null"); } // Initialize adjacency list for vertices if necessary - if (!graph.containsKey(source)) { - graph.put(source, new HashMap<T, Integer>()); + if (!backingGraph.containsKey(sourceVertex)) { + backingGraph.put(sourceVertex, new HashMap<T, Integer>()); } - if (!graph.containsKey(target)) { - graph.put(target, new HashMap<T, Integer>()); + if (!backingGraph.containsKey(targetVertex)) { + backingGraph.put(targetVertex, new HashMap<T, Integer>()); } // Add the edge to the graph - graph.get(source).put(target, distance); + backingGraph.get(sourceVertex).put(targetVertex, distance); // Uncomment this to make the graph undirected // graph.get(target).put(source, distance); @@ -78,16 +81,17 @@ public class Graph<T> { * * @param source * The vertex to test edges for - * @param bp + * @param edgeMatcher * The conditions an edge must match - * @param bc + * @param edgeAction * The action to execute for matching edges */ - public void forAllEdgesMatchingAt(T source, BiPredicate<T, Integer> bp, - BiConsumer<T, Integer> bc) { + public void forAllEdgesMatchingAt(T source, + BiPredicate<T, Integer> edgeMatcher, + BiConsumer<T, Integer> edgeAction) { getEdges(source).forEach((tgt, weight) -> { - if (bp.test(tgt, weight)) { - bc.accept(tgt, weight); + if (edgeMatcher.test(tgt, weight)) { + edgeAction.accept(tgt, weight); } }); } @@ -105,7 +109,7 @@ public class Graph<T> { throw new NullPointerException("The source cannot be null."); } - return Collections.unmodifiableMap(graph.get(source)); + return Collections.unmodifiableMap(backingGraph.get(source)); } /** @@ -114,7 +118,7 @@ public class Graph<T> { * @return The initial vertex of the graph */ public T getInitial() { - return graph.keySet().iterator().next(); + return backingGraph.keySet().iterator().next(); } /** @@ -123,51 +127,59 @@ public class Graph<T> { * * @return a list of edges that constitute the MST */ - public List<Edge<T>> getMinSpanTree() { + public List<Edge<T>> getMinimumSpanningTree() { // Set of all of the currently available edges - Queue<Edge<T>> availEdges = new PriorityQueue<>(10, - (e1, e2) -> e1.getDistance() - e2.getDistance()); + Queue<Edge<T>> availableEdges = new PriorityQueue<>(10, + (leftEdge, rightEdge) -> leftEdge.getDistance() + - rightEdge.getDistance()); // The MST of the graph - List<Edge<T>> minEdges = new ArrayList<>(); + List<Edge<T>> minimumEdges = new ArrayList<>(); // The set of all of the visited vertices. - Set<T> visited = new HashSet<>(); + Set<T> visitedVertexes = new HashSet<>(); // Start at the initial vertex and visit it - IHolder<T> src = new GenHolder<>(getInitial()); - visited.add(src.unwrap(vl -> vl)); + IHolder<T> sourceVertex = new GenHolder<>(getInitial()); + + visitedVertexes.add(sourceVertex.unwrap(vertex -> vertex)); // Make sure we visit all the nodes - while (visited.size() != getVertexCount()) { + while (visitedVertexes.size() != getVertexCount()) { // Grab all edges adjacent to the provided edge - forAllEdgesMatchingAt(src.unwrap(vl -> vl), - (tgt, weight) -> !visited.contains(tgt), - (tgt, weight) -> availEdges.add(new Edge<>( - src.unwrap(vl -> vl), tgt, weight))); + forAllEdgesMatchingAt(sourceVertex.unwrap(vertex -> vertex), + (targetVertex, + vertexWeight) -> !visitedVertexes + .contains(targetVertex), + (targetVertex, + vertexWeight) -> availableEdges.add(new Edge<>( + sourceVertex.unwrap(vertex -> vertex), + targetVertex, vertexWeight))); // Get the edge with the minimum distance - IHolder<Edge<T>> minEdge = new GenHolder<>(availEdges.poll()); + IHolder<Edge<T>> minimumEdge = + new GenHolder<>(availableEdges.poll()); // Only consider edges where we haven't visited the target of // the edge - while (visited - .contains(minEdge.unwrap(vl -> vl.getTarget()))) { - minEdge.transform((vl) -> availEdges.poll()); + while (visitedVertexes.contains( + minimumEdge.unwrap(vertex -> vertex.getTarget()))) { + minimumEdge.transform((edge) -> availableEdges.poll()); } // Add it to our MST - minEdges.add(minEdge.unwrap(vl -> vl)); + minimumEdges.add(minimumEdge.unwrap(edge -> edge)); // Advance to the next node - src.transform((vl) -> minEdge.unwrap(vl1 -> vl1.getTarget())); + sourceVertex.transform((vertex) -> minimumEdge + .unwrap(edge -> edge.getTarget())); // Visit this node - visited.add(src.unwrap(vl -> vl)); + visitedVertexes.add(sourceVertex.unwrap(vertex -> vertex)); } - return minEdges; + return minimumEdges; } /** @@ -176,7 +188,7 @@ public class Graph<T> { * @return A count of the vertices in this graph */ public int getVertexCount() { - return graph.size(); + return backingGraph.size(); } /** @@ -185,37 +197,40 @@ public class Graph<T> { * @return A unmodifiable set of all the vertices in the graph. */ public Set<T> getVertices() { - return Collections.unmodifiableSet(graph.keySet()); + return Collections.unmodifiableSet(backingGraph.keySet()); } /** * Remove the edge starting at the source and ending at the target * - * @param source + * @param sourceVertex * The source vertex for the edge - * @param target + * @param targetVertex * The target vertex for the edge */ - public void removeEdge(T source, T target) { + public void removeEdge(T sourceVertex, T targetVertex) { // Can't remove things w/ null vertices - if (source == null) { - throw new NullPointerException("The vertex 1 cannot be null"); + if (sourceVertex == null) { + throw new NullPointerException( + "The source vertex cannot be null"); } - if (target == null) { - throw new NullPointerException("The vertex 2 cannot be null"); + if (targetVertex == null) { + throw new NullPointerException( + "The target vertex cannot be null"); } // Can't remove if one vertice doesn't exists - if (!graph.containsKey(source)) { + if (!backingGraph.containsKey(sourceVertex)) { throw new NoSuchElementException( - "vertex " + source + " does not exist."); + "vertex " + sourceVertex + " does not exist."); } - if (!graph.containsKey(target)) { + + if (!backingGraph.containsKey(targetVertex)) { throw new NoSuchElementException( - "vertex " + target + " does not exist."); + "vertex " + targetVertex + " does not exist."); } - graph.get(source).remove(target); + backingGraph.get(sourceVertex).remove(targetVertex); // Uncomment this to turn the graph undirected // graph.get(target).remove(source); @@ -226,13 +241,17 @@ public class Graph<T> { * * @return A adjacency map representing this graph */ - public AdjacencyMap<T> toMap() { - AdjacencyMap<T> aMap = new AdjacencyMap<>(graph.keySet()); + public AdjacencyMap<T> toAdjacencyMap() { + AdjacencyMap<T> adjacencyMap = + new AdjacencyMap<>(backingGraph.keySet()); - graph.entrySet().forEach(src -> src.getValue().forEach((tgt, - weight) -> aMap.setWeight(src.getKey(), tgt, weight))); + backingGraph.entrySet().forEach(sourceVertex -> sourceVertex + .getValue() + .forEach((targetVertex, vertexWeight) -> adjacencyMap + .setWeight(sourceVertex.getKey(), targetVertex, + vertexWeight))); - return aMap; + return adjacencyMap; } /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java index 7212e61..be1746f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/ExtensionFileFilter.java @@ -42,8 +42,8 @@ public class ExtensionFileFilter extends FileFilter { public ExtensionFileFilter(String... exts) { extensions = new FunctionalList<>(new ArrayList<>(exts.length)); - for (String ext : exts) { - extensions.add(ext); + for (String extension : exts) { + extensions.add(extension); } } @@ -56,5 +56,4 @@ public class ExtensionFileFilter extends FileFilter { public String getDescription() { return extensions.toString(); } - -} +}
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/ListParameterPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/ListParameterPanel.java index 6272b5f..42c5761 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/ListParameterPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/ListParameterPanel.java @@ -22,46 +22,45 @@ import bjc.utils.gui.layout.VLayout; * The type of data stored in the list */ public class ListParameterPanel<E> extends JPanel { - /** - * Version id for serialization - */ + // Version id for serialization private static final long serialVersionUID = 3442971104975491571L; /** * Create a new panel using the specified actions for doing things * - * @param addAct + * @param addAction * The action that provides items - * @param editAct + * @param editAction * The action that edits items - * @param removeAct + * @param removeAction * The action that removes items */ - public ListParameterPanel(Supplier<E> addAct, Consumer<E> editAct, - Consumer<E> removeAct) { - this(addAct, editAct, removeAct, null); + public ListParameterPanel(Supplier<E> addAction, + Consumer<E> editAction, Consumer<E> removeAction) { + this(addAction, editAction, removeAction, null); } /** * Create a new panel using the specified actions for doing things * - * @param addAct + * @param addAction * The action that provides items - * @param editAct + * @param editAction * The action that edits items - * @param removeAct + * @param removeAction * The action that removes items - * @param defVals + * @param defaultValues * The default values to put in the list */ - public ListParameterPanel(Supplier<E> addAct, Consumer<E> editAct, - Consumer<E> removeAct, FunctionalList<E> defVals) { + public ListParameterPanel(Supplier<E> addAction, + Consumer<E> editAction, Consumer<E> removeAction, + FunctionalList<E> defaultValues) { setLayout(new VLayout(2)); JList<E> list; - if (defVals != null) { - list = SimpleJList.buildFromList(defVals.toIterable()); + if (defaultValues != null) { + list = SimpleJList.buildFromList(defaultValues.toIterable()); } else { list = new JList<>(new DefaultListModel<>()); } @@ -76,11 +75,11 @@ public class ListParameterPanel<E> extends JPanel { JButton removeParam = new JButton("Remove..."); addParam.addActionListener( - (ev) -> ((DefaultListModel<E>) list.getModel()) - .addElement(addAct.get())); + (event) -> ((DefaultListModel<E>) list.getModel()) + .addElement(addAction.get())); editParam.addActionListener( - (ev) -> editAct.accept(list.getSelectedValue())); - removeParam.addActionListener((ev) -> removeAct + (event) -> editAction.accept(list.getSelectedValue())); + removeParam.addActionListener((event) -> removeAction .accept(((DefaultListModel<E>) list.getModel()) .remove(list.getSelectedIndex()))); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java index c85a86e..fd7d05a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java @@ -30,22 +30,22 @@ public class SimpleDialogs { * The title for the dialogs. * @param prompt * The prompt to tell the user what to enter. - * @param lower + * @param lowerBound * The lower integer bound to accept. - * @param upper + * @param upperBound * The upper integer bound to accept. * @return A int within the specified bounds. */ public static int getBoundedInt(Component parent, String title, - String prompt, int lower, int upper) { - return getValue(parent, title, prompt, s -> { + String prompt, int lowerBound, int upperBound) { + return getValue(parent, title, prompt, strang -> { try { - int n = Integer.parseInt(s); - return (n < upper) && (n > lower); + int value = Integer.parseInt(strang); + return (value < upperBound) && (value > lowerBound); } catch (NumberFormatException nfe) { return false; } - } , Integer::parseInt); + }, Integer::parseInt); } /** @@ -67,8 +67,8 @@ public class SimpleDialogs { @SuppressWarnings("unchecked") public static <E> E getChoice(Frame parent, String title, String question, E... choices) { - JDialog jd = new JDialog(parent, title, true); - jd.setLayout(new VLayout(2)); + JDialog mainDialog = new JDialog(parent, title, true); + mainDialog.setLayout(new VLayout(2)); JPanel questionPane = new JPanel(); @@ -83,17 +83,17 @@ public class SimpleDialogs { JButton okButton = new JButton("Ok"); JButton cancelButton = new JButton("Cancel"); - okButton.addActionListener(e -> jd.dispose()); - cancelButton.addActionListener(e -> jd.dispose()); + okButton.addActionListener((event) -> mainDialog.dispose()); + cancelButton.addActionListener((event) -> mainDialog.dispose()); buttonPane.add(cancelButton); buttonPane.add(okButton); - jd.add(questionPane); - jd.add(buttonPane); + mainDialog.add(questionPane); + mainDialog.add(buttonPane); - jd.pack(); - jd.setVisible(true); + mainDialog.pack(); + mainDialog.setVisible(true); return (E) questionChoices.getSelectedItem(); } @@ -111,14 +111,14 @@ public class SimpleDialogs { */ public static int getInt(Component parent, String title, String prompt) { - return getValue(parent, title, prompt, s -> { + return getValue(parent, title, prompt, strang -> { try { - Integer.parseInt(s); + Integer.parseInt(strang); return true; } catch (NumberFormatException nfe) { return false; } - } , Integer::parseInt); + }, Integer::parseInt); } /** @@ -150,23 +150,24 @@ public class SimpleDialogs { * The title for dialogs. * @param prompt * The prompt to tell the user what to enter. - * @param p + * @param inputValidator * A predicate to determine if a input is valid. - * @param f + * @param inputTransformer * The function to transform the string into a value. * @return The value parsed from a string. */ public static <E> E getValue(Component parent, String title, - String prompt, Predicate<String> p, Function<String, E> f) { - String inp = getString(parent, title, prompt); + String prompt, Predicate<String> inputValidator, + Function<String, E> inputTransformer) { + String inputString = getString(parent, title, prompt); - while (!p.test(inp)) { + while (!inputValidator.test(inputString)) { showError(parent, "I/O Error", "Please enter a valid value"); - inp = getString(parent, title, prompt); + inputString = getString(parent, title, prompt); } - return f.apply(inp); + return inputTransformer.apply(inputString); } /** @@ -198,10 +199,10 @@ public class SimpleDialogs { */ public static boolean getYesNo(Component parent, String title, String question) { - int res = JOptionPane.showConfirmDialog(parent, question, title, - JOptionPane.YES_NO_OPTION); + int dialogResult = JOptionPane.showConfirmDialog(parent, question, + title, JOptionPane.YES_NO_OPTION); - return (res == JOptionPane.YES_OPTION ? true : false); + return (dialogResult == JOptionPane.YES_OPTION ? true : false); } /** @@ -211,12 +212,12 @@ public class SimpleDialogs { * The parent component for dialogs. * @param title * The title for dialogs. - * @param err + * @param errorMessage * The error to show the user. */ public static void showError(Component parent, String title, - String err) { - JOptionPane.showMessageDialog(parent, err, title, + String errorMessage) { + JOptionPane.showMessageDialog(parent, errorMessage, title, JOptionPane.ERROR_MESSAGE); } -} +}
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java index 39d944b..9648762 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java @@ -16,7 +16,7 @@ import bjc.utils.exceptions.FileNotChosenException; * */ public class SimpleFileChooser { - private static File doOpenFile(Component par, String title, + private static File doOpenFile(Component parent, String title, JFileChooser files) { files.setDialogTitle(title); @@ -24,11 +24,11 @@ public class SimpleFileChooser { while (!success) { try { - maybeDoOpenFile(par, files); + maybeDoOpenFile(parent, files); success = true; } catch (FileNotChosenException e) { - SimpleDialogs.showError(par, "I/O Error", + SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to open"); } } @@ -36,7 +36,7 @@ public class SimpleFileChooser { return files.getSelectedFile(); } - private static File doSaveFile(Component par, String title, + private static File doSaveFile(Component parent, String title, JFileChooser files) { files.setDialogTitle(title); @@ -44,11 +44,11 @@ public class SimpleFileChooser { while (!success) { try { - maybeDoSaveFile(par, files); + maybeDoSaveFile(parent, files); return files.getSelectedFile(); } catch (FileNotChosenException e) { - SimpleDialogs.showError(par, "I/O Error", + SimpleDialogs.showError(parent, "I/O Error", "Please pick a file to save to"); } } @@ -60,23 +60,23 @@ public class SimpleFileChooser { * Prompt the user with a "Open File..." dialog. Keeps prompting them * until they pick a file. * - * @param par + * @param parent * The component to use as the parent for the dialog. * @param title * The title of the dialog to prompt with. * @return The file the user has chosen. */ - public static File getOpenFile(Component par, String title) { + public static File getOpenFile(Component parent, String title) { JFileChooser files = new JFileChooser(); - return doOpenFile(par, title, files); + return doOpenFile(parent, title, files); } /** * Prompt the user with a "Open File..." dialog. Keeps prompting them * until they pick a file. * - * @param par + * @param parent * The component to use as the parent for the dialog. * @param title * The title of the dialog to prompt with. @@ -84,33 +84,33 @@ public class SimpleFileChooser { * The list of file extensions the file should have. * @return The file the user has chosen. */ - public static File getOpenFile(Component par, String title, + public static File getOpenFile(Component parent, String title, String... extensions) { JFileChooser files = new JFileChooser(); files.addChoosableFileFilter(new ExtensionFileFilter(extensions)); - return doOpenFile(par, title, files); + return doOpenFile(parent, title, files); } /** * Prompt the user with a "Save File..." dialog. * - * @param par + * @param parent * The component to use as the parent for the dialog. * @param title * The title of the dialog to prompt with. * @return The file the user chose. */ - public static File getSaveFile(Component par, String title) { + public static File getSaveFile(Component parent, String title) { JFileChooser files = new JFileChooser(); - return doSaveFile(par, title, files); + return doSaveFile(parent, title, files); } /** * Prompt the user with a "Save File..." dialog. * - * @param par + * @param parent * The component to use as the parent for the dialog. * @param title * The title of the dialog to prompt with. @@ -118,30 +118,28 @@ public class SimpleFileChooser { * The extensions of the files the user can choose. * @return The file the user chose. */ - public static File getSaveFile(Component par, String title, + public static File getSaveFile(Component parent, String title, String... extensions) { JFileChooser files = new JFileChooser(); files.addChoosableFileFilter(new ExtensionFileFilter(extensions)); - return doSaveFile(par, title, files); + return doSaveFile(parent, title, files); } - private static void maybeDoOpenFile(Component par, JFileChooser files) - throws FileNotChosenException { - int res = files.showSaveDialog(par); + private static void maybeDoOpenFile(Component parent, + JFileChooser files) throws FileNotChosenException { + int dialogResult = files.showSaveDialog(parent); - if (res != JFileChooser.APPROVE_OPTION) { + if (dialogResult != JFileChooser.APPROVE_OPTION) { throw new FileNotChosenException(); } } - private static void maybeDoSaveFile(Component par, JFileChooser files) - throws FileNotChosenException { - int res = files.showSaveDialog(par); + private static void maybeDoSaveFile(Component parent, + JFileChooser files) throws FileNotChosenException { + int dialogResult = files.showSaveDialog(parent); - System.out.println("Result: " + res); - - if (res != JFileChooser.APPROVE_OPTION) { + if (dialogResult != JFileChooser.APPROVE_OPTION) { throw new FileNotChosenException(); } } @@ -149,18 +147,18 @@ public class SimpleFileChooser { /** * Prompt the user with a "Open File..." dialog. * - * @param par + * @param parent * The component to use as the parent for the dialog. * @param title * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ - public static File maybeOpenFile(Component par, String title) { + public static File maybeOpenFile(Component parent, String title) { JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { - maybeDoOpenFile(par, files); + maybeDoOpenFile(parent, files); } catch (FileNotChosenException e) { } @@ -170,18 +168,18 @@ public class SimpleFileChooser { /** * Prompt the user with a "Save File..." dialog. * - * @param par + * @param parent * The component to use as the parent for the dialog. * @param title * The title of the dialog to prompt with. * @return The file if the user chose one or null if they didn't. */ - public static File maybeSaveFile(Component par, String title) { + public static File maybeSaveFile(Component parent, String title) { JFileChooser files = new JFileChooser(); files.setDialogTitle(title); try { - maybeDoSaveFile(par, files); + maybeDoSaveFile(parent, files); } catch (FileNotChosenException e) { } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java index 614cf33..4695318 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java @@ -17,12 +17,12 @@ public class SimpleJList { * @param <E> * The type of data in the JList * - * @param ls + * @param listSource * The list to populate the JList with. * @return A JList populated with the elements from ls. */ - public static <E> JList<E> buildFromList(Iterable<E> ls) { - return new JList<>(buildModel(ls)); + public static <E> JList<E> buildFromList(Iterable<E> listSource) { + return new JList<>(buildModel(listSource)); } /** @@ -31,15 +31,15 @@ public class SimpleJList { * @param <E> * The type of data in the list model * - * @param ls + * @param listSource * The list to fill the list model from. * @return A list model populated with the elements from ls. */ - public static <E> ListModel<E> buildModel(Iterable<E> ls) { - DefaultListModel<E> dlm = new DefaultListModel<>(); + public static <E> ListModel<E> buildModel(Iterable<E> listSource) { + DefaultListModel<E> defaultModel = new DefaultListModel<>(); - ls.forEach(dlm::addElement); + listSource.forEach(defaultModel::addElement); - return dlm; + return defaultModel; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java index 9c6feef..ddf5492 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleTitledBorder.java @@ -10,9 +10,7 @@ import javax.swing.border.TitledBorder; * */ public class SimpleTitledBorder extends TitledBorder { - /** - * Version ID for serialization - */ + // Version ID for serialization private static final long serialVersionUID = -5655969079949148487L; /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java index 6f43ba9..368f8be 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java @@ -42,13 +42,13 @@ public class ExtensionFileFilter implements FilenameFilter { public ExtensionFileFilter(String... exts) { extensions = new FunctionalList<>(new ArrayList<>(exts.length)); - for (String ext : exts) { - extensions.add(ext); + for (String extension : exts) { + extensions.add(extension); } } @Override - public boolean accept(File dir, String name) { + public boolean accept(File directory, String name) { return extensions.anyMatch(name::endsWith); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java index c12119f..a8df3b9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java @@ -19,20 +19,20 @@ public class SimpleFileDialog { /** * Prompt the user to pick a file to open * - * @param par + * @param parent * The parent of the file picker * @param title * The title of the file picker * @return The file the user picked */ - public static File getOpenFile(Frame par, String title) { - return getOpenFile(par, title, (String[]) null); + public static File getOpenFile(Frame parent, String title) { + return getOpenFile(parent, title, (String[]) null); } /** * Prompt the user to pick a file to open * - * @param par + * @param parent * The parent of the file picker * @param title * The title of the file picker @@ -40,43 +40,44 @@ public class SimpleFileDialog { * The extensions to accept as valid * @return The file the user picked */ - public static File getOpenFile(Frame par, String title, + public static File getOpenFile(Frame parent, String title, String... extensions) { - FileDialog fd = new FileDialog(par, title, FileDialog.LOAD); + FileDialog fileDialog = + new FileDialog(parent, title, FileDialog.LOAD); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); - fd.setFilenameFilter(filter); + fileDialog.setFilenameFilter(filter); } - fd.setVisible(true); + fileDialog.setVisible(true); - while (fd.getFile() == null) { - SimpleDialogs.showError(par, "File I/O Error", + while (fileDialog.getFile() == null) { + SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); - fd.setVisible(true); + fileDialog.setVisible(true); } - return fd.getFiles()[0]; + return fileDialog.getFiles()[0]; } /** * Prompt the user to pick a file to save * - * @param par + * @param parent * The parent of the file picker * @param title * The title of the file picker * @return The file the user picked */ - public static File getSaveFile(Frame par, String title) { - return getSaveFile(par, title, (String[]) null); + public static File getSaveFile(Frame parent, String title) { + return getSaveFile(parent, title, (String[]) null); } /** * Prompt the user to pick a file to save * - * @param par + * @param parent * The parent of the file picker * @param title * The title of the file picker @@ -84,23 +85,24 @@ public class SimpleFileDialog { * The extensions to accept as valid * @return The file the user picked */ - public static File getSaveFile(Frame par, String title, + public static File getSaveFile(Frame parent, String title, String... extensions) { - FileDialog fd = new FileDialog(par, title, FileDialog.SAVE); + FileDialog fileDialog = + new FileDialog(parent, title, FileDialog.SAVE); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); - fd.setFilenameFilter(filter); + fileDialog.setFilenameFilter(filter); } - fd.setVisible(true); + fileDialog.setVisible(true); - while (fd.getFile() == null) { - SimpleDialogs.showError(par, "File I/O Error", + while (fileDialog.getFile() == null) { + SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to save to."); - fd.setVisible(true); + fileDialog.setVisible(true); } - return fd.getFiles()[0]; + return fileDialog.getFiles()[0]; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java index 0130eee..d8a60ed 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/AutosizeLayout.java @@ -10,9 +10,7 @@ import java.awt.GridLayout; * */ public class AutosizeLayout extends GridLayout { - /** - * Version id for serialization - */ + // Version id for serialization private static final long serialVersionUID = -2495693595953396924L; /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java index 83b3793..c986310 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/HLayout.java @@ -10,18 +10,16 @@ import java.awt.GridLayout; * */ public class HLayout extends GridLayout { - /** - * Version id for serialization - */ + // Version ID for serialization private static final long serialVersionUID = 1244964456966270026L; /** * Create a new horizontal layout with the specified number of columns. * - * @param cols + * @param columns * The number of columns in this layout. */ - public HLayout(int cols) { - super(1, cols); + public HLayout(int columns) { + super(1, columns); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java index 23ab61e..5951ba5 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/layout/VLayout.java @@ -10,9 +10,7 @@ import java.awt.GridLayout; * */ public class VLayout extends GridLayout { - /** - * Version id for serialization - */ + // Version ID for serializations private static final long serialVersionUID = -6417962941602322663L; /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/AST.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/AST.java index 9ced090..4bfb469 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/AST.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/AST.java @@ -6,7 +6,7 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; -import bjc.utils.funcdata.ITreePart.TreeLinearizationMethod; +import bjc.utils.funcdata.bst.ITreePart.TreeLinearizationMethod; /** * A simple binary tree meant for use as an AST @@ -55,36 +55,37 @@ public class AST<T> { /** * Traverse an AST * - * @param tlm + * @param linearizationMethod * The way to traverse the tree - * @param con + * @param action * The function to call on each traversed element */ - public void traverse(TreeLinearizationMethod tlm, Consumer<T> con) { + public void traverse(TreeLinearizationMethod linearizationMethod, + Consumer<T> action) { if (left != null && right != null) { - switch (tlm) { + switch (linearizationMethod) { case INORDER: - left.traverse(tlm, con); - con.accept(token); - right.traverse(tlm, con); + left.traverse(linearizationMethod, action); + action.accept(token); + right.traverse(linearizationMethod, action); break; case POSTORDER: - left.traverse(tlm, con); - right.traverse(tlm, con); - con.accept(token); + left.traverse(linearizationMethod, action); + right.traverse(linearizationMethod, action); + action.accept(token); break; case PREORDER: - con.accept(token); - left.traverse(tlm, con); - right.traverse(tlm, con); + action.accept(token); + left.traverse(linearizationMethod, action); + right.traverse(linearizationMethod, action); break; default: throw new IllegalArgumentException( - "Got a invalid tree linearizer " + tlm - + ". WAT"); + "Got a invalid tree linearizer " + + linearizationMethod + ". WAT"); } } else { - con.accept(token); + action.accept(token); } } @@ -95,107 +96,131 @@ public class AST<T> { * The final value of the collapsed tree * @param <T2> * - * @param tokenTransform + * @param tokenTransformer * The function to transform nodes into data - * @param nodeTransform + * @param nodeTransformer * A map of functions for operator collapsing - * @param resultTransform + * @param resultTransformer * The function for transforming the result * @return The collapsed value of the tree */ - public <E, T2> E collapse(Function<T, T2> tokenTransform, - Function<T, BinaryOperator<T2>> nodeTransform, - Function<T2, E> resultTransform) { - return resultTransform - .apply(internalCollapse(tokenTransform, nodeTransform)); + public <E, T2> E collapse(Function<T, T2> tokenTransformer, + Function<T, BinaryOperator<T2>> nodeTransformer, + Function<T2, E> resultTransformer) { + return resultTransformer.apply( + internalCollapse(tokenTransformer, nodeTransformer)); } /* * Internal recursive collapser */ - protected <T2> T2 internalCollapse(Function<T, T2> tokenTransform, - Function<T, BinaryOperator<T2>> nodeTransform) { + protected <T2> T2 internalCollapse(Function<T, T2> tokenTransformer, + Function<T, BinaryOperator<T2>> nodeTransformer) { if (left == null && right == null) { - return tokenTransform.apply(token); + return tokenTransformer.apply(token); } else { - T2 leftCollapsed = left.internalCollapse(tokenTransform, - nodeTransform); - T2 rightCollapsed = right.internalCollapse(tokenTransform, - nodeTransform); + T2 leftCollapsed; + + if (left == null) { + leftCollapsed = null; + } else { + leftCollapsed = left.internalCollapse(tokenTransformer, + nodeTransformer); + } + + T2 rightCollapsed; + if (right == null) { + rightCollapsed = null; + } else { + rightCollapsed = right.internalCollapse(tokenTransformer, + nodeTransformer); + } - return nodeTransform.apply(token).apply(leftCollapsed, + return nodeTransformer.apply(token).apply(leftCollapsed, rightCollapsed); } } @Override public String toString() { - StringBuilder sb = new StringBuilder(); + StringBuilder builder = new StringBuilder(); - internalToString(sb, -1); + internalToString(builder, -1); - return sb.toString(); + return builder.toString(); } /** * Internal version of toString for proper rendering * - * @param sb + * @param builder * The string rendering being built * @param indentLevel * The current level to indent the tree */ - protected void internalToString(StringBuilder sb, int indentLevel) { - indentNLevels(sb, indentLevel); + protected void internalToString(StringBuilder builder, + int indentLevel) { + indentNLevels(builder, indentLevel); if (left == null && right == null) { - sb.append("Node: "); - sb.append(token.toString()); - sb.append("\n"); + builder.append("Node: "); + builder.append(token.toString()); + builder.append("\n"); } else { - sb.append("Node: "); - sb.append(token.toString()); - sb.append("\n"); - - left.internalToString(sb, indentLevel + 2); - right.internalToString(sb, indentLevel + 2); + builder.append("Node: "); + builder.append(token.toString()); + builder.append("\n"); + + if (left != null) { + left.internalToString(builder, indentLevel + 2); + } else { + indentNLevels(builder, indentLevel + 2); + builder.append("No left node\n"); + } + if (right != null) { + right.internalToString(builder, indentLevel + 2); + } else { + indentNLevels(builder, indentLevel + 2); + builder.append("No right node\n"); + } } } /** * Indent a string n levels * - * @param sb + * @param builder * The string to indent - * @param n + * @param levels * The number of levels to indent */ - protected static void indentNLevels(StringBuilder sb, int n) { - for (int i = 0; i <= n; i++) { - sb.append("\t"); + protected static void indentNLevels(StringBuilder builder, + int levels) { + for (int i = 0; i <= levels; i++) { + builder.append("\t"); } } /** * Execute a transform on selective nodes of the tree * - * @param transformPred + * @param transformerPredicate * The predicate to pick nodes to transform * @param transformer * The thing to use to transform the nodes */ - public void selectiveTransform(Predicate<T> transformPred, + public void selectiveTransform(Predicate<T> transformerPredicate, UnaryOperator<T> transformer) { - if (transformPred.test(token)) { + if (transformerPredicate.test(token)) { token = transformer.apply(token); } if (left != null) { - left.selectiveTransform(transformPred, transformer); + left.selectiveTransform(transformerPredicate, transformer); } if (right != null) { - right.selectiveTransform(transformPred, transformer); + right.selectiveTransform(transformerPredicate, transformer); } } @@ -210,17 +235,18 @@ public class AST<T> { * @return The AST with transformed tokens */ public <E> AST<E> transmuteAST(Function<T, E> tokenTransformer) { - AST<E> l = null; - AST<E> r = null; + AST<E> leftBranch = null; + AST<E> rightBranch = null; if (left != null) { - l = left.transmuteAST(tokenTransformer); + leftBranch = left.transmuteAST(tokenTransformer); } if (right != null) { - r = right.transmuteAST(tokenTransformer); + rightBranch = right.transmuteAST(tokenTransformer); } - return new AST<>(tokenTransformer.apply(token), l, r); + return new AST<>(tokenTransformer.apply(token), leftBranch, + rightBranch); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java index 95ced43..287c8a9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java @@ -11,12 +11,12 @@ public interface IPrecedent { /** * Create a new object with set precedence * - * @param prec + * @param precedence * The precedence of the object to handle * @return A new object with set precedence */ - public static IPrecedent newSimplePrecedent(int prec) { - return () -> prec; + public static IPrecedent newSimplePrecedent(int precedence) { + return () -> precedence; } /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java index 12f6891..46f5f1d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/RuleBasedConfigReader.java @@ -51,62 +51,63 @@ public class RuleBasedConfigReader<E> { /** * Add a pragma to this reader * - * @param pragName + * @param pragmaName * The name of the pragma to add - * @param pragAct + * @param pragmaAction * The function to execute when this pragma is read */ - public void addPragma(String pragName, - BiConsumer<FunctionalStringTokenizer, E> pragAct) { - pragmas.put(pragName, pragAct); + public void addPragma(String pragmaName, + BiConsumer<FunctionalStringTokenizer, E> pragmaAction) { + pragmas.put(pragmaName, pragmaAction); } /** * Run a stream through this reader * - * @param is + * @param inputStream * The stream to get input - * @param initState + * @param initialState * The initial state of the reader * @return The final state of the reader */ - public E fromStream(InputStream is, E initState) { - Scanner scn = new Scanner(is); + public E fromStream(InputStream inputStream, E initialState) { + Scanner inputSource = new Scanner(inputStream); - E stat = initState; + E state = initialState; - while (scn.hasNextLine()) { - String ln = scn.nextLine(); + while (inputSource.hasNextLine()) { + String line = inputSource.nextLine(); - if (ln.equals("")) { - endRule.accept(stat); + if (line.equals("")) { + endRule.accept(state); continue; - } else if (ln.startsWith("\t")) { + } else if (line.startsWith("\t")) { continueRule.accept(new FunctionalStringTokenizer( - ln.substring(1), " "), stat); + line.substring(1), " "), state); } else { - FunctionalStringTokenizer stk = - new FunctionalStringTokenizer(ln, " "); + FunctionalStringTokenizer tokenizer = + new FunctionalStringTokenizer(line, " "); - String nxtToken = stk.nextToken(); - if (nxtToken.equals("#")) { + String nextToken = tokenizer.nextToken(); + if (nextToken.equals("#")) { // Do nothing, this is a comment - } else if (nxtToken.equals("pragma")) { - String tk = stk.nextToken(); + } else if (nextToken.equals("pragma")) { + String token = tokenizer.nextToken(); - pragmas.getOrDefault(tk, (strk, ras) -> { + pragmas.getOrDefault(token, (tokenzer, stat) -> { throw new UnknownPragmaException( - "Unknown pragma " + tk); - }).accept(stk, stat); + "Unknown pragma " + token); + }).accept(tokenizer, state); } else { - startRule.accept(stk, new Pair<>(nxtToken, stat)); + startRule.accept(tokenizer, + new Pair<>(nextToken, state)); } } } - scn.close(); + inputSource.close(); - return stat; + return state; } /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java index 3bb6bed..0ca1879 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -21,23 +21,23 @@ import bjc.utils.funcutils.StringUtils; public class ShuntingYard<E> { private final class TokenShunter implements Consumer<String> { - private FunctionalList<E> outp; + private FunctionalList<E> output; private Deque<String> stack; private Function<String, E> transform; - public TokenShunter(FunctionalList<E> outp, Deque<String> stack, + public TokenShunter(FunctionalList<E> outpt, Deque<String> stack, Function<String, E> transform) { - this.outp = outp; + this.output = outpt; this.stack = stack; this.transform = transform; } @Override public void accept(String token) { - if (ops.containsKey(token)) { + if (operators.containsKey(token)) { while (!stack.isEmpty() && isHigherPrec(token, stack.peek())) { - outp.add(transform.apply(stack.pop())); + output.add(transform.apply(stack.pop())); } stack.push(token); @@ -45,12 +45,12 @@ public class ShuntingYard<E> { stack.push(token); } else if (StringUtils.containsOnly(token, "\\)")) { while (stack.peek().equals(token.replace(')', '('))) { - outp.add(transform.apply(stack.pop())); + output.add(transform.apply(stack.pop())); } stack.pop(); } else { - outp.add(transform.apply(token)); + output.add(transform.apply(token)); } } } @@ -81,8 +81,8 @@ public class ShuntingYard<E> { private final int precedence; - private Operator(int p) { - precedence = p; + private Operator(int prec) { + precedence = prec; } /* @@ -99,70 +99,72 @@ public class ShuntingYard<E> { /** * Holds all the shuntable operations */ - private Map<String, IPrecedent> ops; + private Map<String, IPrecedent> operators; /** * Create a new shunting yard with a default set of operators */ public ShuntingYard() { - ops = new HashMap<>(); + operators = new HashMap<>(); - ops.put("+", Operator.ADD); - ops.put("-", Operator.SUBTRACT); - ops.put("*", Operator.MULTIPLY); - ops.put("/", Operator.DIVIDE); + operators.put("+", Operator.ADD); + operators.put("-", Operator.SUBTRACT); + operators.put("*", Operator.MULTIPLY); + operators.put("/", Operator.DIVIDE); } /** * Add an operator to the list of shuntable operators * - * @param tok + * @param operatorToken * The token representing the operator - * @param i + * @param precedence * The precedence of the operator to add */ - public void addOp(String tok, int i) { - this.addOp(tok, IPrecedent.newSimplePrecedent(i)); + public void addOp(String operatorToken, int precedence) { + this.addOp(operatorToken, + IPrecedent.newSimplePrecedent(precedence)); } /** * Add an operator to the list of shuntable operators * - * @param tok + * @param token * The token representing the operator - * @param prec + * @param precedence * The precedence of the operator */ - public void addOp(String tok, IPrecedent prec) { - ops.put(tok, prec); + public void addOp(String token, IPrecedent precedence) { + operators.put(token, precedence); } - private boolean isHigherPrec(String op, String sub) { - return (ops.containsKey(sub) && ops.get(sub).getPrecedence() >= ops - .get(op).getPrecedence()); + private boolean isHigherPrec(String operator, String rightOperator) { + return (operators.containsKey(rightOperator) && operators + .get(rightOperator).getPrecedence() >= operators + .get(operator).getPrecedence()); } /** * Transform a string of tokens from infix notation to postfix * - * @param inp + * @param input * The string to transform - * @param transform + * @param tokenTransformer * The function to use to transform strings to tokens * @return A list of tokens in postfix notation */ - public FunctionalList<E> postfix(FunctionalList<String> inp, - Function<String, E> transform) { - FunctionalList<E> outp = new FunctionalList<>(); + public FunctionalList<E> postfix(FunctionalList<String> input, + Function<String, E> tokenTransformer) { + FunctionalList<E> output = new FunctionalList<>(); Deque<String> stack = new LinkedList<>(); - inp.forEach(new TokenShunter(outp, stack, transform)); + input.forEach(new TokenShunter(output, stack, tokenTransformer)); while (!stack.isEmpty()) { - outp.add(transform.apply(stack.pop())); + output.add(tokenTransformer.apply(stack.pop())); } - return outp; + return output; } /** @@ -172,6 +174,6 @@ public class ShuntingYard<E> { * The token representing the operator */ public void removeOp(String tok) { - ops.remove(tok); + operators.remove(tok); } }
\ No newline at end of file diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java index 6339d8c..42d5a9d 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -23,9 +23,9 @@ public class TreeConstructor { * * @param <T> * The elements of the parse tree - * @param toks + * @param tokens * The list of tokens to build a tree from - * @param opPredicate + * @param operatorPredicate * The predicate to use to determine if something is a * operator * @return A AST from the expression @@ -34,9 +34,10 @@ public class TreeConstructor { * {@link TreeConstructor#constructTree(FunctionalList, Predicate, Predicate, Function)} * instead */ - public static <T> AST<T> constructTree(FunctionalList<T> toks, - Predicate<T> opPredicate) { - return constructTree(toks, opPredicate, (op) -> false, null); + public static <T> AST<T> constructTree(FunctionalList<T> tokens, + Predicate<T> operatorPredicate) { + return constructTree(tokens, operatorPredicate, (op) -> false, + null); } /** @@ -46,15 +47,15 @@ public class TreeConstructor { * * @param <T> * The elements of the parse tree - * @param toks + * @param tokens * The list of tokens to build a tree from - * @param opPredicate + * @param operatorPredicate * The predicate to use to determine if something is a * operator - * @param isSpecialOp + * @param isSpecialOperator * The predicate to use to determine if an operator needs * special handling - * @param handleSpecialOp + * @param handleSpecialOperator * The function to use to handle special case operators * @return A AST from the expression * @@ -62,51 +63,55 @@ public class TreeConstructor { * interface. Maybe there's a better way to express how that * works */ - public static <T> AST<T> constructTree(FunctionalList<T> toks, - Predicate<T> opPredicate, Predicate<T> isSpecialOp, - Function<Deque<AST<T>>, AST<T>> handleSpecialOp) { - GenHolder<Pair<Deque<AST<T>>, AST<T>>> initState = + public static <T> AST<T> constructTree(FunctionalList<T> tokens, + Predicate<T> operatorPredicate, Predicate<T> isSpecialOperator, + Function<Deque<AST<T>>, AST<T>> handleSpecialOperator) { + GenHolder<Pair<Deque<AST<T>>, AST<T>>> initialState = new GenHolder<>(new Pair<>(new LinkedList<>(), null)); - toks.forEach((ele) -> { - if (opPredicate.test(ele)) { - initState.transform((par) -> { - Deque<AST<T>> lft = par.merge((deq, ast) -> deq); + tokens.forEach((element) -> { + if (operatorPredicate.test(element)) { + initialState.transform((pair) -> { + Deque<AST<T>> queuedASTs = + pair.merge((queue, currentAST) -> queue); - AST<T> mergedAST = par.merge((deq, ast) -> { + AST<T> mergedAST = pair.merge((queue, currentAST) -> { AST<T> newAST; - if (isSpecialOp.test(ele)) { - newAST = handleSpecialOp.apply(deq); + if (isSpecialOperator.test(element)) { + newAST = handleSpecialOperator.apply(queue); } else { - AST<T> right = deq.pop(); - AST<T> left = deq.pop(); - newAST = new AST<>(ele, left, right); + AST<T> rightAST = queue.pop(); + AST<T> leftAST = queue.pop(); + + newAST = new AST<>(element, leftAST, rightAST); } - deq.push(newAST); + queue.push(newAST); return newAST; }); Pair<Deque<AST<T>>, AST<T>> newPair = - new Pair<>(lft, mergedAST); + new Pair<>(queuedASTs, mergedAST); return newPair; }); } else { - AST<T> newAST = new AST<>(ele); + AST<T> newAST = new AST<>(element); - initState.doWith((par) -> par.doWith((deq, ast) -> { - deq.push(newAST); - })); + initialState.doWith( + (pair) -> pair.doWith((queue, currentAST) -> { + queue.push(newAST); + })); - initState.transform((par) -> { - return (Pair<Deque<AST<T>>, AST<T>>) par - .apply((d) -> d, (a) -> newAST); + initialState.transform((pair) -> { + return (Pair<Deque<AST<T>>, AST<T>>) pair.apply( + (queue) -> queue, (currentAST) -> newAST); }); } }); - return initState.unwrap((par) -> par.merge((deq, ast) -> ast)); + return initialState.unwrap( + (pair) -> pair.merge((queue, currentAST) -> currentAST)); } } |
