Java: Random permutation without importing java.util

422 views Asked by At

There are many different instructions to do random permutation on the Internet, but they all use libraries. Is there any way to do random permutation without using any built-in library? I know how to generate random numbers using Math.random(). Does generating random permutation have to do with Math.random()? Shuffling looks so complicated to me.

My goal is if I run the programme by 'java randompermutation 3', then the programme returns either 1,2,3 or 1,3,2, or 3,1,2, or 3,2,1, or 2,3,1, or 2,1,3

2

There are 2 answers

0
guninvalid On

One algorithm for sorting an array is based on selection sort and is called selection shuffle. Go through the array and for each index, pick a random index following it and swap those two indices. Since this looks a bit like homework, I will refrain from giving any actual code, but this is a solution.

2
John On

Could you do something like the example shown below

public class Main {
    public static void main(String[] args) throws Exception {
        Integer[] input = new Integer[] { 1, 2, 3 };
        Integer[] shuffleInput = shuffle(input);

        for (int i=0; i<shuffleInput.length; i++) {
            System.out.print(shuffleInput[i]);
        }
    }

    public static Integer[] shuffle(Integer[] input) {
        Integer[] inputCopy = input.clone();;
        Integer[] output = new Integer[input.length];

        for (int i=0; i<output.length; i++) {
            // Find and get a random element
            int randPicker = (int)(System.currentTimeMillis() % inputCopy.length);
            output[i] = inputCopy[randPicker];

            // Remove selected element from copy
            Integer[] aux = new Integer[inputCopy.length - 1];
            System.arraycopy(inputCopy, 0, aux, 0, randPicker);
            if (inputCopy.length != randPicker) {
                System.arraycopy(inputCopy, randPicker + 1, aux, randPicker, inputCopy.length - randPicker - 1);
            }
            inputCopy = aux;
        }

        return output;
    }
}

This code takes a list of Integer of any size as input, and return a list with the mixed values.

If the list will always be 3 numbers, it could be a simpler version.

EDITED: This version does not use Math.random() or any other java.util.