Java acquires specific interval random numbers and produces non-repeating random numbers

Source: Internet
Author: User
Tags array length

Problem

There is a need, in such an array String[] arr = new String[]{"电商", "互联网", "小程序", "网络推广", "文化", "教育", "造型设计", "服装设计"}; , to randomly take n options and do not repeat, n is random and within the range of 1-m, where M is a definite number and m<= array length.

Ideas

Take a random number from a specific interval

// 从区间[1,4]随机取一个数new Random();int num = random.nextInt(41;// 从区间[MIN,MAX]随机取一个数(MAX>MIN,MIN>=0)new Random();int num = random.nextInt1) + MIN;// random.nextInt(num)取值范围是 [0,num)

There are two ways to take the n elements randomly from an array of length m.

    1. Generates n non-repeating random numbers [0,m-1], which are evaluated from the array according to the subscript
    2. The order of the elements in the array is scrambled, take the first n number, that is, the number of the first n, each and the element is exchanged, random?

Idea 1

intStartarray[] = {0,1,2,3,4,5,6,7,8,9};//seed ArrayintN =Ten;//random numberintResultarray[] =New int[Ten];//Results are stored inside for(inti =0; i < N; i++) {intSeed =Random(0, Startarray.length-i);//generated from the remaining random numbersResultarray[i] = Startarray[seed];//assignment to the result arrayStartarray[seed] = Startarray[startarray.lengthI1];//Replace the position where the random number was created with the unchecked value. }

Idea 2

// 
Solve
Random random =NewRandom ();intnum = random.Nextint(4) +1; System. out.println("num:"+ num); string[] arr =Newstring[]{"e-commerce","Internet","Small Program","Network Promotion","Culture","Education","Styling Design","Costume Design"};intLen = arr.length; for(inti =0; i < num; ++i) {intIDX = random.Nextint(len-i); System. out.println(Arr[idx]);    String tmp = Arr[idx]; ARR[IDX] = arr[len-i-1]; Arr[len-i-1] = tmp;}
Reference

A fast algorithm for generating n non-repeating random numbers

Java acquires specific interval random numbers and produces non-repeating random numbers

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.