Generate an 8-digit random, non-repeating number

Source: Internet
Author: User

Package com. jjinfo. common. util; import java. util. arrays; import java. util. random;/*****/public class RandomNumberGenerator {/*** this is a typical Random shuffling algorithm. * The process is to select an alternative array and put it into the target array, and remove the selected array from the alternative array (put it to the end, and narrow down the selection area) * algorithm time complexity O (n) * @ return random 8 is a non-repeated array */public static String generateNumber () {String no = ""; // initialize the alternative array int [] defaultNums = new int [10]; for (int I = 0; I <defanumnums. length; I ++) {defanumnums [I] = I;} Random random = new Random (); int [] nums = new int [LENGTH]; // The optional part of the default array length int canBeUsed = 10; // fill in the target array for (int I = 0; I <nums. length; I ++) {// Save the randomly selected number to the destination array int index = random. nextInt (canBeUsed); nums [I] = defaultNums [index]; // throw the used number to the end of the alternative array, and reduce the 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 <10; I ++) {// System. out. println (generateNumber (); System. out. println (generateNumber2 ());}}}

 

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.