By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,806 Members | 1,361 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,806 IT Pros & Developers. It's quick & easy.

Help with random permutation and arrays

P: 1
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!
Expand|Select|Wrap|Line Numbers
  1. import java.util.Random;
  2. import java.util.ArrayList;
  3.  
  4. /**
  5.    This class generates permutations of a sequence of integers 
  6.    1...length.
  7. */
  8. public class PermutationGenerator
  9. {
  10.    /**
  11.       Construct a PermutationGenerator object.
  12.       @param length the length of the permutations generated
  13.       by this generator.
  14.    */
  15.    public PermutationGenerator(int length)
  16.    {
  17.       generator = new Random();
  18.       this.length = length;
  19.    }
  20.  
  21.    /**
  22.       Gets the next permutation.
  23.       @return the array containing the next permutation
  24.    */
  25.    public int[] nextPermutation()
  26.    {
  27.       int[] result = new int[length];
  28.       ArrayList<Integer> choices = new ArrayList<Integer>();
  29.  
  30.  
  31.       // Put the numbers 1 through "length" into the choices array
  32.       for (int i = 0; i < length; i++)
  33.       {
  34.          choices.add(i+1);
  35.  
  36.       }
  37.  
  38.       // Now pick numbers from the choices array and put them
  39.       // into the results array.
  40.       for (int i = 0; i < length; i++)
  41.       {
  42.           while(length<9){
  43.           result[i] = generator.nextInt(choices.size());
  44.  
  45.           choices.remove(i);
  46.       }
  47.       }
  48.  
  49.       return result;
  50.    }
  51.  
  52.    private Random generator;
  53.    private int length;
  54. }
And the tester class:
Expand|Select|Wrap|Line Numbers
  1. /**
  2.    This class prints 5 permutations of the numbers 1 through 10.
  3. */
  4. public class PermutationPrinter
  5. {  
  6.    public static void main(String[] args)
  7.    {  
  8.       PermutationGenerator gen = new PermutationGenerator(10);      
  9.  
  10.       for (int i = 1; i <= 5; i++)
  11.       {  
  12.          for (int n : gen.nextPermutation())
  13.             System.out.print(" " +  n);
  14.          System.out.println();
  15.       }
  16.    }
  17. }
Sep 26 '12 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.