I want a class, that take in a possitive integer and produce a iterator that let me iterate through all possible of permutation of a list of possitive numbers under the positive
try this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.IntStream;
public class Paermulator {
private final List list = new ArrayList<>();
public Paermulator(int i) {
int[] array = IntStream.iterate(0, x -> x + 1)
.limit(i)
.toArray();
populateList(array, 0);
}
private void populateList(int[] array, int index) {
if (index >= array.length - 1) {
int[] temp = new int[array.length];
System.arraycopy(array, 0, temp, 0, array.length);
list.add(temp);
return;
}
for (int i = index; i < array.length; i++) {
int temp = array[index];
array[index] = array[i];
array[i] = temp;
populateList(array, index + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
public List getList() {
return list;
}
public Iterator getItrator() {
return list.iterator();
}
// main method is for testing output
public static void main(String[] args) {
//printing output
new Paermulator(5).getList().stream().forEach(x -> System.out.println(Arrays.toString(x)));
}
}
This class accepts an int in constructor and creates an array and pass the array to populateList
method this method populate the list with all possible permutations.
and you can get Iterator
using getIterator
method .