50 lines
1.3 KiB
Java
50 lines
1.3 KiB
Java
package com.fabiosalvini.permutations;
|
|
|
|
import java.util.function.Consumer;
|
|
|
|
import static com.fabiosalvini.utils.ArrayUtils.swap;
|
|
|
|
/**
|
|
* Class to generate all permutations of an array of elements.
|
|
* <p>
|
|
* The computation is based on Heap's algorithm (https://en.wikipedia.org/wiki/Heap%27s_algorithm).
|
|
*/
|
|
public class PermutationsGenerator {
|
|
|
|
private final long[] elements;
|
|
private final int[] indexes;
|
|
private final Consumer<long[]> consumer;
|
|
|
|
/**
|
|
* Create a new generator.
|
|
*
|
|
* @param elements the array of elements.
|
|
* @param consumer the consumer that will receive every permutation.
|
|
*/
|
|
public PermutationsGenerator(long[] elements, Consumer<long[]> consumer) {
|
|
this.elements = elements;
|
|
this.consumer = consumer;
|
|
indexes = new int[elements.length];
|
|
}
|
|
|
|
/**
|
|
* Compute all permutations using Heap's algorithm.
|
|
*/
|
|
public void compute() {
|
|
consumer.accept(elements);
|
|
int i = 0;
|
|
while (i < elements.length) {
|
|
if (indexes[i] < i) {
|
|
swap(elements, i % 2 == 0 ? 0 : indexes[i], i);
|
|
consumer.accept(elements);
|
|
indexes[i]++;
|
|
i = 0;
|
|
} else {
|
|
indexes[i] = 0;
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|