Advertisement
brilliant_moves

RandomizeNumberArray.java

Oct 25th, 2012
619
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.72 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class RandomizeNumberArray {
  4.  
  5.     /**
  6.     *       Program:        RandomizeNumberArray.java
  7.     *       Purpose:        Randomize an array of integers
  8.     *       Creator:        Chris Clarke
  9.     *       Created:        25.10.2012
  10.     */
  11.  
  12.     public static void main(String[] args) {
  13.         Scanner scan = new Scanner(System.in);
  14.         int min = 0; // makes the range from 0 to max-1
  15.         int max = 0;
  16.  
  17.         System.out.print("Enter size of the array: ");
  18.  
  19.         try {
  20.             max = scan.nextInt();
  21.  
  22.         } catch (Exception x) {
  23.             System.out.println("Not a whole number!");
  24.             System.exit(1);
  25.         } // end try/catch
  26.  
  27.         // randomize the order of an array of linear values
  28.         int[] shuffled = randomizeOrder(min, max);
  29.  
  30.         System.out.println(); // new line
  31.  
  32.         // display contents of array
  33.         for (int i=0; i<max; i++) {
  34.             System.out.print(shuffled[i]+" ");
  35.         } // end for
  36.  
  37.         System.out.println(); // new line
  38.     } // end main
  39.  
  40.     public static int[] randomizeOrder(int min, int max) {
  41.  
  42.         /**
  43.         *   max is the array size
  44.         *   when min=0, range is 0 to max-1
  45.         *   shuffle or rearrange the array values
  46.         */
  47.            
  48.         int[] theArray, results;
  49.         theArray = new int[max];
  50.         results = new int[max];
  51.  
  52.         int r;  // a random number
  53.  
  54.         // initialise the array
  55.         for (int i=0; i<max; i++)
  56.             theArray[i]=i+min; // when min=1, range is 1 to max inclusive
  57.                        // when min=0, range is 0 to max-1 inclusive
  58.  
  59.         // pick n numbers
  60.         for (int i=0; i<max; i++) {
  61.             // range 1 to 49, 1 to 48 etc
  62.             r = (int) ((max-i) * Math.random());
  63.             // store results
  64.             results[i] = theArray[r];
  65.             // move last number in theArray to position r
  66.             theArray[r] = theArray[max-1-i];
  67.         } // end for
  68.  
  69.         return results;
  70.  
  71.     } // end randomizeOrder
  72. } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement