Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class RandomizeNumberArray {
- /**
- * Program: RandomizeNumberArray.java
- * Purpose: Randomize an array of integers
- * Creator: Chris Clarke
- * Created: 25.10.2012
- */
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int min = 0; // makes the range from 0 to max-1
- int max = 0;
- System.out.print("Enter size of the array: ");
- try {
- max = scan.nextInt();
- } catch (Exception x) {
- System.out.println("Not a whole number!");
- System.exit(1);
- } // end try/catch
- // randomize the order of an array of linear values
- int[] shuffled = randomizeOrder(min, max);
- System.out.println(); // new line
- // display contents of array
- for (int i=0; i<max; i++) {
- System.out.print(shuffled[i]+" ");
- } // end for
- System.out.println(); // new line
- } // end main
- public static int[] randomizeOrder(int min, int max) {
- /**
- * max is the array size
- * when min=0, range is 0 to max-1
- * shuffle or rearrange the array values
- */
- int[] theArray, results;
- theArray = new int[max];
- results = new int[max];
- int r; // a random number
- // initialise the array
- for (int i=0; i<max; i++)
- theArray[i]=i+min; // when min=1, range is 1 to max inclusive
- // when min=0, range is 0 to max-1 inclusive
- // pick n numbers
- for (int i=0; i<max; i++) {
- // range 1 to 49, 1 to 48 etc
- r = (int) ((max-i) * Math.random());
- // store results
- results[i] = theArray[r];
- // move last number in theArray to position r
- theArray[r] = theArray[max-1-i];
- } // end for
- return results;
- } // end randomizeOrder
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement