如何从给定范围中选择随机值

我正在尝试创建一个Android应用程序,它将在给定范围内生成随机序列值(在这种情况下为整数)(但在它们之间相等)并在简单的TextView中显示它们

假设我们的范围为R = [1,2,3,4,5,6,7,8,9,10,11,12,13]

每次按“生成”按钮,我想随机生成5个不同的结果

每个“生成”的示例:

  • 4,9,2,12,10
  • 5,1,6,8,13
  • 10,4,6,8,2
  • 等等…

编辑(现在工作)感谢您的帮助!

public class random extends Activity { static final Integer[] data = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8 }; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Random r = new Random(); Set mySet = new HashSet(); while (mySet.size() < 5) { int idx = r.nextInt(data.length); mySet.add(data[idx]); } String text = ""; for (Integer i : mySet) { text = text + i + ", "; } TextView Numbers = (TextView)findViewById(R.id.shownumbers); Numbers.setText(text); } } 

 Random r = new Random(); Set mySet = new HashSet(); while (mySet.size() < 5) { int idx = r.nextInt() mySet.add(data[idx]); } 

数据包含您的范围编号。

 String text = ""; for (Integer i : mySet) { text = text + i + ", "; } 

在TextView中设置此文本。

在编辑代码中:

 int idx = r.nextInt(); 

需要改为:

 int idx = r.nextInt(data.length); 

因为您想从数据中选择随机索引。

如果我理解正确,那么所有数字都应该是唯一的。 您可以使用要绘制的范围填充列表。 每次从中选择一个值时,都应该从列表中删除它,这样就不会再次选择它。 我希望这个描述足够清楚。 如果没有,我会提供一些代码。

 int low = ...; int high = ...; List choices = new LinkedList(); for (int i = low; i <= high; i++) { choices.add(i); } Collections.shuffle(choices); int[] choices = new int[] { choices.get(0), choices.get(1), choices.get(2), choices.get(3), choices.get(4) }; 
 final StringBuilder builder = new StringBuilder(); final Random r = new Random(System.currentTimeMillis()); final Set numbers = new HashSet(); public String getRandomNumbers(int count,int min, int max) { if(count > (max - min) || (max < min)) throw new IllegalArgumentException("There is an error with the parameters provided"); builder.setLength(0); //Clear StringBuilder numbers.clear(); //Clear the number list int i=0; while( i < count ) { int aRandomNumber = (r.nextInt() % max) +min; if(numbers.contains(aRandomNumber)) // If we have seen this number already continue; else { i++; numbers.add(aRandomNumber); builder.append(aRandomNumber); //Add number to string if( i < (count-1) ) builder.append(", "); // Add a comma if it's not the last number } } String output = builder.toString(); builder.setLength(0); //A polite clearing numbers.clear(); return output; } 
 public int[] generateSeries(){ int[] R = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; int [] newarray=new int[5]; Collections.shuffle(Arrays.asList(R)); for(int i=0;i<5;i++) { newarray[i]=R[i]; System.out.println("values => "+R[i]); } return newarray; 

希望充分利用你….