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.
- Generates n non-repeating random numbers [0,m-1], which are evaluated from the array according to the subscript
- 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