简体   繁体   中英

math.random in java

Hi consider that I have a for loop : for(int i = 0;i<4;i++)

in the for loop ,I want to print the random of numbers from 0 till 3 and the result include just 3 numbers from this.and each time that for loop execute ,the result of math.random must be different ie, I have 4 numbers : (1,2,3,4) and I want to have 4 results after for loop executes: [1,2,3] [1,2,4] [2,3,4] [4,1,3] how can i produce these numbers? thanks

Here's an idea:

  1. make a "master" list that will hold all your needed elements, from 0 to 3 (or 1 to 4, whatever you need)
  2. shuffle the list using Collections.shuffle
  3. turn that list into a stack
  4. pop everything from stack
  5. repeat 2-4 as needed

Step 4. is the one where you will get all your elements randomly, without duplication.

Note: in step 3., you can also create a new list from the master list instead of a stack if it seems easier, but the basic premise is the same.

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