Class PermutationIterator

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. The hasNext() method is O(1). The runtime of the next() 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 Details

    • 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 Details

    • hasNext

      public boolean hasNext()
      Checks if this PermutationIterator has more Permutations.
      Specified by:
      hasNext in interface Iterator<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:
      next in interface Iterator<Permutation>
      Returns:
      The Permutation for the next iteration.
      Throws:
      NoSuchElementException - if hasNext() is false