09-27-2012, 10:36 AM #1 (permalink) Status: Senior Member Posts: 151,118 Write a program that produces random permutations of the numbers 1 to 10.? Write a program that produces random permutations of the numbers 1 to 10. To generate a random permutation, you need to fill an array with the numbers 1 to 10 so that no two entries of the array have the same contents. You could do it by brute force, by calling Random.nextInt()until it produces a value that is not yet in the array. Instead, you should implement a smart method: Make a new ArrayList of Integers and fill it with the numbers 1 to 10. Make a new array of int to hold the permuation In a loop that repeats 10 times, pick one of remaining numbers at random from the ArrayList, remove it from the ArrayList, and append it to the permutation array. here is the code I have so far for my permutation generator class: import java.util.Random; import java.util.ArrayList; /** This class generates permutations of a sequence of integers 1...length. */ public class PermutationGenerator { private int length; /** 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 choices = new ArrayList(); // Put the numbers 1 through "length" into the choices array for (int i = 1; i < length; i++) { choices.add(i); } // Now pick numbers from the choices array and put them // into the results array. // for (int i = 0; i < length; i++) // { // // } for (int num = 1; num < length; num++) { int pos = generator.nextInt(choices.size()); result.add(choices.get(pos)); choices.remove(pos); } result.add(choices.get(0)); return result; } private Random generator; } I keep getting a "Cannot invoke add(Integer) on the array type int[]" exception. How ccan I fix this?
 09-27-2012, 10:36 AM #2 (permalink) Status: Senior Member Posts: 151,118 Write a program that produces random permutations of the numbers 1 to 10.? Result is an array and does not support adding elements this way. Do result[num-1]=choices.get(pos); result[length]=choices.get(0);
 more..

 Bookmarks

 Thread Tools Display Modes Linear Mode

 Similar Threads Thread Thread Starter Forum Replies Last Post Toto Programming 1 07-12-2013 02:07 PM Lubnh Programming 0 05-10-2013 10:06 AM James Programming 0 02-28-2013 05:04 PM Titilayo Programming 0 02-08-2013 06:06 PM Unknown_User Programming 1 01-07-2012 09:36 AM

 Contact Us - Coding - Advertise with us - Archive - Coding Forum - Top