开发者

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 i.e., 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜