From 843329de434bb334d90927c4d22345373a388530 Mon Sep 17 00:00:00 2001 From: bculkin2442 Date: Tue, 2 Jul 2019 18:05:22 -0400 Subject: Rename package root The package root is now bjc, not io.github.bculkin2442. --- src/main/java/bjc/data/GeneratingIterator.java | 60 ++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/main/java/bjc/data/GeneratingIterator.java (limited to 'src/main/java/bjc/data/GeneratingIterator.java') diff --git a/src/main/java/bjc/data/GeneratingIterator.java b/src/main/java/bjc/data/GeneratingIterator.java new file mode 100644 index 0000000..9adda6f --- /dev/null +++ b/src/main/java/bjc/data/GeneratingIterator.java @@ -0,0 +1,60 @@ +package bjc.data; + +import java.util.Iterator; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; + +/** + * An iterator that generates a series of elements from a single element. + * + * @author bjculkin + * + * @param + * The type of element generated. + */ +public class GeneratingIterator implements Iterator { + /* Our current state. */ + private E state; + /* The function to use to transition states. */ + private UnaryOperator transtion; + /* The predicate to indicate where to stop. */ + private Predicate stpper; + + /** + * Create a new generative iterator. + * + * @param initial + * The initial state of the generator. + * + * @param transition + * The function to apply to the state. + * + * @param stopper + * The predicate applied to the current state to determine when + * to stop. + */ + public GeneratingIterator(E initial, UnaryOperator transition, Predicate stopper) { + state = initial; + transtion = transition; + stpper = stopper; + } + + @Override + public boolean hasNext() { + return stpper.test(state); + } + + /* + * @NOTE + * + * As this currently is, it only works correctly assuming that next() is + * only called when hasNext() is true. Should we safeguard against + * people who are not doing the right thing? + */ + @Override + public E next() { + state = transtion.apply(state); + + return state; + } +} -- cgit v1.2.3