0

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);
    }
}
Nicktar
  • 5,548
  • 1
  • 28
  • 43
Cloud Walker
  • 314
  • 1
  • 6
  • 18
  • 4
    Method 2 is arguably faster, but don't use bubble sort or random numbers. Just shuffle the array – OneCricketeer Feb 05 '20 at 03:56
  • 1
    https://stackoverflow.com/questions/15196363/java-how-do-i-create-an-int-array-with-randomly-shuffled-numbers-in-a-given-ra – OneCricketeer Feb 05 '20 at 03:58
  • 1
    If you want pseudorandomness (or random-like) in java, efficient won't be the problem: Math.random() is a know source of artifacts. Your mileage may vary, but don't use it for applications with great dependency on random behavior. But for demo and testing, Math.random() should be just fine. See: https://peteroupc.github.io/random.html – Victor Polo De Gyves Montero Feb 05 '20 at 04:16

0 Answers0