- java.lang.Object
-
- org.cicirello.permutations.PermutationIterator
-
- All Implemented Interfaces:
Iterator<Permutation>
public class PermutationIterator extends Object implements Iterator<Permutation>
Iterator over all permutations of a specified length, n, of the integers in the interval [0,n). The runtime of the constructors is O(n), where n is the permutation length. ThehasNext()method is O(1). The runtime of thenext()method is O(n), as it does O(n) swaps in the worst-case, and regardless of number of swaps it returns a copy (an O(n) operation) of the internally maintained Permutation object so the caller can safely modify the returned Permutation without risk of interfering with the operation of the Iterator.
-
-
Constructor Summary
Constructors Constructor Description PermutationIterator(int n)Initializes a PermutationIterator to iterate over all permutations of a given length.PermutationIterator(Permutation p)Initializes a PermutationIterator to iterate over all permutations the same length as a given permutation.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanhasNext()Checks if this PermutationIterator has more Permutations.Permutationnext()Gets the Permutation for the next iteration.-
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface java.util.Iterator
forEachRemaining, remove
-
-
-
-
Constructor Detail
-
PermutationIterator
public PermutationIterator(int n)
Initializes a PermutationIterator to iterate over all permutations of a given length. Specifically, it iterates over permutations of the first n integers, i.e., the integers in the interval [0, n-1]. The first permutation in the iteration is chosen randomly.- Parameters:
n- The length of the permutations.
-
PermutationIterator
public PermutationIterator(Permutation p)
Initializes a PermutationIterator to iterate over all permutations the same length as a given permutation. Specifically, it iterates over permutations of the first n integers, i.e., the integers in the interval [0, n-1). The first permutation in the iteration is specified as a parameter.- Parameters:
p- The first permutation in the iteration.
-
-
Method Detail
-
hasNext
public boolean hasNext()
Checks if this PermutationIterator has more Permutations.- Specified by:
hasNextin interfaceIterator<Permutation>- Returns:
- true if and only if this PermutationIterator has more Permutations to iterate over.
-
next
public Permutation next()
Gets the Permutation for the next iteration.- Specified by:
nextin interfaceIterator<Permutation>- Returns:
- The Permutation for the next iteration.
- Throws:
NoSuchElementException- if hasNext() is false
-
-