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:
- make a "master" list that will hold all your needed elements, from 0 to 3 (or 1 to 4, whatever you need)
- shuffle the list using
Collections.shuffle
- turn that list into a stack
- pop everything from stack
- 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.
精彩评论