I am trying to write a program that produces random permutations of the numbers 1 to 10. It goes into and ArrayList and I have to take it from the ArrayList and put it in an array. It is working without any errors, but all the numbers print 0. I'm not sure why it isn't transferring the numbers correctly to the array. Any suggestions are greatly appreciated!
And the tester class:
Code:
import java.util.Random;
import java.util.ArrayList;
/**
This class generates permutations of a sequence of integers
1...length.
*/
public class PermutationGenerator
{
/**
Construct a PermutationGenerator object.
@param length the length of the permutations generated
by this generator.
*/
public PermutationGenerator(int length)
{
generator = new Random();
this.length = length;
}
/**
Gets the next permutation.
@return the array containing the next permutation
*/
public int[] nextPermutation()
{
int[] result = new int[length];
ArrayList<Integer> choices = new ArrayList<Integer>();
// Put the numbers 1 through "length" into the choices array
for (int i = 0; i < length; i++)
{
choices.add(i+1);
}
// Now pick numbers from the choices array and put them
// into the results array.
for (int i = 0; i < length; i++)
{
while(length<9){
result[i] = generator.nextInt(choices.size());
choices.remove(i);
}
}
return result;
}
private Random generator;
private int length;
}
Code:
/**
This class prints 5 permutations of the numbers 1 through 10.
*/
public class PermutationPrinter
{
public static void main(String[] args)
{
PermutationGenerator gen = new PermutationGenerator(10);
for (int i = 1; i <= 5; i++)
{
for (int n : gen.nextPermutation())
System.out.print(" " + n);
System.out.println();
}
}
}