简体   繁体   English

Java中的math.random

[英]math.random in java

Hi consider that I have a for loop : for(int i = 0;i<4;i++) 您好,我有一个for循环: 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? for循环中,我想打印0到3之间的数字,结果只包括3个数字。每次执行for循环时,math.random的结果必须不同,即我有4个数字:(1,2,3,4),我想在for循环执行后得到4个结果:[1,2,3] [1,2,4] [2,3,4] [4,1,3]我如何产生这些数字? 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) 制作一个“主”列表,其中包含您需要的所有元素,从0到3(或1到4,无论您需要什么)
  2. shuffle the list using Collections.shuffle 使用Collections.shuffle 随机播放列表
  3. turn that list into a stack 将该列表变成堆栈
  4. pop everything from stack 从堆栈中弹出所有内容
  5. repeat 2-4 as needed 根据需要重复2-4

Step 4. is the one where you will get all your elements randomly, without duplication. 步骤4.是您将随机获得所有元素而不重复的步骤。

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. 注意:在第3步中,如果看起来比较简单,您也可以从主列表中创建一个新列表,而不是从堆栈中创建一个新列表,但是基本前提是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM