160511. Method of generating 8-bit random non-repeating number

Source: Internet
Author: User

Import Java.util.Random;

public class RandomNumberGenerator {
/**
* This is a typical random shuffle algorithm. The process is to select one from the alternate array into the target array, remove the selected array from the alternate array (put to the last, and narrow the selection) algorithm time complexity O (n)
* @return Random 8 is a non-repeating array
* @author RICK
*/
public static String Generatenumber () {
String no = "";
Initializing an alternate array
int[] defaultnums = new INT[10];
for (int i = 0; i < defaultnums.length; i++) {
Defaultnums[i] = i;
}

Random random = new random ();
int[] Nums = new Int[length];
The part length that can be selected in the default array
int canbeused = 10;
Populating the target array
for (int i = 0; i < nums.length; i++) {
Storing randomly selected numbers in the target array
int index = Random.nextint (canbeused);
Nums[i] = Defaultnums[index];
Throws the used number to the alternate array at the end and reduces the optional area
Swap (index, canBeUsed-1, defaultnums);
canbeused--;
}
if (Nums.length > 0) {
for (int i = 0; i < nums.length; i++) {
No + = Nums[i];
}
}

return no;
}

private static final int LENGTH = 8;

private static void swap (int i, int J, int[] nums) {
int temp = Nums[i];
Nums[i] = Nums[j];
NUMS[J] = temp;
}

public static String GenerateNumber2 () {
String no = "";
int num[] = new INT[8];
int c = 0;
for (int i = 0; i < 8; i++) {
Num[i] = new Random (). Nextint (10);
c = Num[i];
for (int j = 0; J < i; J + +) {
if (num[j] = = c) {
i--;
Break
}
}
}
if (Num.length > 0) {
for (int i = 0; i < num.length; i++) {
No + = Num[i];
}
}
return no;
}

public static void Main (string[] args) {
for (int i = 0; i < i++) {
System.out.println (Generatenumber ());
System.out.println (GenerateNumber2 ());
}
}
}

160511. Method of generating 8-bit random non-repeating number

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.