org.paukov.combinatorics3.SimplePermutationGenerator Maven / Gradle / Ivy
Show all versions of combinatoricslib3 Show documentation
/**
* Combinatorics Library 3
* Copyright 2016 Dmytro Paukov [email protected]
*/
package org.paukov.combinatorics3;
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This generator generates all possible permutations of the specified initial
* vector
*
* A permutation is an ordering of a set in the context of all possible
* orderings. For example, the set containing the first three digits, 123, has
* six permutations: 123, 132, 213, 231, 312, and 321.
*
* This is an example of the permutations of 3 string items (apple, orange,
* cherry):
*
*
*
*
*
* // Create the initial vector of 3 elements (apple, orange, cherry)
* ICombinatoricsVector<String> originalVector = Factory
* .createVector(new String[] { "apple", "orange", "cherry" });
*
* // Create the permutation generator by calling the appropriate method in the
* // Factory class
* Generator<String> gen = Factory.createPermutationGenerator(originalVector);
*
* // Print the result
* for (ICombinatoricsVector<String> perm : gen)
* System.out.println(perm);
*
*
*
*
*
* And the result
*
*
*
*
* CombinatoricsVector=([apple, orange, cherry], size=3)
* CombinatoricsVector=([apple, cherry, orange], size=3)
* CombinatoricsVector=([cherry, apple, orange], size=3)
* CombinatoricsVector=([cherry, orange, apple], size=3)
* CombinatoricsVector=([orange, cherry, apple], size=3)
* CombinatoricsVector=([orange, apple, cherry], size=3)
*
*
*
*
*
* @author Dmytro Paukov
* @version 2.0
* @param
* Type of the elements in the permutations
*/
class SimplePermutationGenerator implements IGenerator> {
final boolean hasDuplicates;
final boolean treatAsIdentical;
final List originalVector;
/**
* Constructor
*
* @param vector
* Vector which is used for permutation generation
* @param treatAsIdentical
* True if the generator should treat the vector as identical
*/
SimplePermutationGenerator(Collection vector,
boolean treatAsIdentical) {
hasDuplicates = PermutationGenerator.hasDuplicates(vector);
this.treatAsIdentical = treatAsIdentical;
originalVector = new ArrayList<>(vector);
}
/**
* Creates an iterator
*
* @see org.paukov.combinatorics3.Generator#iterator()
*/
@Override
public Iterator> iterator() {
if (isDuplicateIterator())
return new DuplicatedPermutationIterator<>(this);
else
return new SimplePermutationIterator<>(this);
}
@Override
public Stream> stream() {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator(), 0), false);
}
boolean isDuplicateIterator() {
return (!treatAsIdentical && hasDuplicates);
}
}