0

I need to write a program that produces a single random permutation of the numbers 1 - 10. If possible, no methods or extra include libraries. Simple as can be. Here is what I have so far.

import java.util.Scanner;
public class SwitchingNum {
public static void main(String[] args) {
    int num = 10;
    Scanner in = new Scanner(System.in);
    int[] tempArray = new int[10];
    int currentSize = tempArray.length;
    System.out.print("First Array: ");
    for(int i = 0; i < num; i++){
        tempArray[i] = i + 1;
        System.out.print(tempArray[i] + " ");
    }
    int[] permArray = new int[tempArray.length];
    System.out.println();
    System.out.print("Second Array: ");
    for (int i = 0; i < permArray.length; i ++){
        permArray[i] = tempArray[(int) (Math.random() * currentSize -1)];
        for (int j = i; j < currentSize -1; j++){
            tempArray[i] = tempArray[i+1];
        }
        currentSize--;
        System.out.print(permArray[i] + " ");
    }
}
}
nits.kk
  • 5,204
  • 4
  • 33
  • 55
  • Here is a helpful vid explaining what you need: https://youtu.be/U0nvXHh7o-w?t=4m36s – Ain Apr 02 '17 at 19:31
  • 1
    Your current solution is O(n^2) and not uniformly random. – Ain Apr 02 '17 at 19:39
  • Possible duplicate of [Generate an uniform random permutation](http://stackoverflow.com/questions/7902391/generate-an-uniform-random-permutation) – Leon Apr 02 '17 at 19:43

1 Answers1

0

An easy way to shuffle an array is the Fisher–Yates shuffle. Just copy the original array into your permArray and then do:

Random rand = new Random();
for(int i = 0;  i < permArray.length - 1; i++) {
    int swapPosition = rand.nextInt(permArray.length - i) + i;
    int tmp = permArray[i];
    permArray[i] = permArray[swapPosition]
    permArray[swapPosition] = tmp;
}

Don't forget to import java.util.Random. For more info, you can take a look at this question.

Community
  • 1
  • 1
Leon
  • 2,926
  • 1
  • 25
  • 34