mardi 4 février 2020

How to generate 256 numbers from 0-255, no repetitions, in java?

What's the most efficient algorithm for generating 256 numbers randomly from 0-255 with no repetitions? I have a few ideas, but I don't think they are very efficient.

Method 1: Create an array and generate a random number at every index. Then check repetitions. If the number is repeated, generate another one until it's not.

public static void method() {

        int[] nums = new int[256];
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            nums[i] =(byte) (int) (Math.random() * 256);
            while (j != i) {
                nums[i] = (int) (Math.random() * 256);
                for (j = 0; j < i; j++) {
                    if (nums[i] == nums[j]) {
                        break;
                    }
                }
            }
        }
        for(intx: nums) {
            System.out.println(x);
        }
 } 

Methods 2: Create an array, filled with numbers from 0-255(no reps) in order. Then in a for-loop, generate 2 random numbers x, y and swap the elements in the array at index x and y.

public void method(){
    int[] nums = new int[256];
    for(int i=0; i<nums.length;i++){
        nums[i]=i;
    }
    int random=1000; //this number determines how "random" the order is.
    for(int i=0;i<random; i++){
        int x=(int) (Math.random() * 256);
        int y=(int) (Math.random() * 256);
        int temp;
        temp=nums[x];
        nums[x]=nums[y];
        nums[y]=temp;
    }
    for(int x : nums){
        System.out.println(x);
    }
}



Aucun commentaire:

Enregistrer un commentaire