简体   繁体   中英

Generate Unique 4-digit random number without using Random class

I need help in generating a 4-digit random number between 1-8 without using the random class OR the collections.shuffle().

Thanks in advance.

This is one way you can do it:

  • Generate an array of 0 - 9.
  • Randomly shuffle the array.
  • Pick the first four element from the array to construct the 4-digit number.

int[] nums = {0,1,2,3,4,5,6,7,8,9};

//Shuffle array
for(int x=0; x<nums.length; x++){
    int i = (int)(Math.random()*10);  //generate random 0-9
    int temp = nums[x];
    nums[x] = nums[i];
    nums[i] = temp;
}

From the shuffled array, simply get the first 4 elements and construct your unique number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM