Advertisement
brilliant_moves

RandomizeNumberArray3.java

May 10th, 2015
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.64 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class RandomizeNumberArray3 {
  4.  
  5.     /**
  6.     *       Program:        RandomizeNumberArray3.java
  7.     *       Purpose:        Randomize order of array of contiguous integers
  8.     *       Creator:        Chris Clarke
  9.     *       Created:        10.05.2015
  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.         Integer[] unshuffled;
  17.         Integer[] shuffled;
  18.  
  19.         System.out.println("*** Randomize Number Array ***");
  20.         System.out.print("Enter size of the array: ");
  21.  
  22.         try {
  23.             max = scan.nextInt();
  24.             unshuffled = new Integer[max];
  25.         } catch (Exception x) {
  26.             System.out.println("Not a positive whole number!");
  27.             return;
  28.         } // end try/catch
  29.  
  30.         System.out.print("Enter initial value (0 or 1): ");
  31.         try {
  32.             min = scan.nextInt();
  33.         } catch (Exception x) {
  34.             System.out.println("Not a positive whole number!");
  35.             return;
  36.         } // end try/catch
  37.  
  38.         // initialise the array
  39.         for (int i=0; i<max; i++)
  40.             unshuffled[i] = i + min;
  41.  
  42.         // function call to randomize the array
  43.         shuffled = randomize(unshuffled, min, max);
  44.  
  45.         System.out.println(Arrays.toString(shuffled));
  46.  
  47.     } // main()
  48.  
  49.     public static Integer[] randomize(Integer[] unshuffled, int min, int max) {
  50.         // randomize the order of an array of linear values
  51.  
  52.         Integer[] shuffled;
  53.         List<Integer> li = new ArrayList<Integer>();
  54.         li = Arrays.asList(unshuffled);
  55.         Collections.shuffle(li);
  56.         shuffled = new Integer[max];
  57.         for (int i=0; i<li.size(); i++)
  58.             shuffled[i] = li.get(i);
  59.  
  60.         return shuffled;
  61.  
  62.     } // randomize()
  63.  
  64. } // class RandomizeNumberArray3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement