Advertisement
dimipan80

Randomize the Numbers 1…N

Aug 8th, 2014
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. /* Write a program that enters in integer n and prints the numbers 1, 2, …, n in random order.
  2.  * You might need to use arrays */
  3.  
  4. import java.util.Random;
  5. import java.util.Scanner;
  6.  
  7. public class _12_RandomizeTheNumbers1toN {
  8.  
  9.     public static void main(String[] args) {
  10.         // TODO Auto-generated method stub
  11.         Scanner scan = new Scanner(System.in);
  12.         System.out.print("Enter a whole positive number, bigger from 1, for N: ");
  13.         int numN = scan.nextInt();
  14.         scan.close();
  15.  
  16.         if (numN > 1) {
  17.             boolean[] randomNums = new boolean[numN + 1];
  18.             randomNums[0] = true;
  19.             Random generator = new Random();
  20.             for (int i = 1; i < randomNums.length; i++) {
  21.                 int random = 1 + generator.nextInt(numN);
  22.                 if (randomNums[random]) {
  23.                     i--;
  24.                 } else {
  25.                     randomNums[random] = true;
  26.                     System.out.print(random);
  27.                     if (i < randomNums.length - 1) {
  28.                         System.out.print(" ");
  29.                     }
  30.                 }
  31.             }
  32.  
  33.         } else {
  34.             System.out.println("Error! - Invalid Input number!!!");
  35.         }
  36.     }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement