This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
More Random Thoughts...
Posted by Matt Gerrans on November 07, 2001 at 6:03 PM
And here is a variation on the same theme, using arrays of int s (since Lists of primatives can be cumbersome). This is probably faster than using a list too.
import java.util.*;class Shuffler { // or use a generator? Random rand = new Random(); int [] getShuffledArray( int [] items ) { int [] shuffled = new int[ items.length ]; int [] unshuffled = new int[ items.length ]; for( int i = 0; i < items.length; i++ ) unshuffled[i] = items[i]; int index; int length = unshuffled.length; for( int i = 0; i < items.length; i++ ) { index = rand.nextInt(length); shuffled[i] = unshuffled[index]; if( index != length1 ) unshuffled[index] = unshuffled[length1]; length; } return shuffled; } int [] getShuffledArray( int length ) { int [] ordered = new int[ length ]; for( int i = 0; i < length; i++ ) // Start with ordered array. ordered[i] = i; return getShuffledArray( ordered ); } public static void main( String[] args ) { int size = 108; if( args.length > 0 ) size = Integer.parseInt(args[0]); int [] numbers = (new Shuffler()).getShuffledArray(size); System.out.print( numbers[0] ); for( int i = 1; i < size; i++ ) System.out.print( ", " + numbers[i] ); } }
 mfg > I would build a List (LinkedList may perform better in this case than ArrayList), not an array, of all the unique values, then use Random to get an index into the list (from 0 to whatever its current size is), remove the value at that index and return it.
>  mfg > > > This is an interesting approach, but as the list of numbers generated gets closer to completion it will take more and more time for the generator to find a number that has not been generated yet. This, I think, would really bog down the program for a process that should be a bit less demanding on the CPU. > > > You are right that it is possible to get repeats, just by using them on their own. > > > I know it sounds inefficient, but you could maintain a vector of "numbers generated so far". Each time you generate a new number, add it to the vector. The inefficiency comes from having to check each vector element and see if the number generated matches any of them. If it does, you will need to generate a new number. > > > I will have a think about how it could be done more elegantly. >
Replies:
