-1

可能重复:
使用随机数生成器对整数进行随机排列
如何生成随机数,但它不会产生相同的数字

我创建了 3 个随机数我希望这 3 个数字不重复

例如,如果第一个随机数 = 到 3,我不想要第二个数字或第三个数字 = 到 3
并获取最小数并在 3 个按钮上随机数 10 在按钮中设置这些数字

package com.math4kids;

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class MinNumber extends Activity {
public Button result1, result2, result3;
public Random random = new Random();
int[] array1 = new int[3] ;
int minimum = array1[0]; //sets the first to be the smallest
int num1,num2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.minnumber);

    result1 = (Button)findViewById(R.id.result1);
    result2= (Button)findViewById(R.id.result2);
    result3= (Button)findViewById(R.id.result3);



    array1[0] = random.nextInt(10) + 1;
    array1[1] = random.nextInt(10) + 1;;
    array1[2] = random.nextInt(10) + 1;;


    for (int i = 0; i < array1.length; i++) //goes through your array
    {
         if (array1[i] < array1[0]) //checks and replaces if necessary
         {
            minimum = array1[i];   


         }
         if(array1[0]==minimum){
             num1=array1[1];
             num2=array1[2];
         }
         if(array1[1]==minimum){
             num1=array1[0];
             num2=array1[2];
         }
         if(array1[2]==minimum){
             num1=array1[1];
             num2=array1[0];
         }
            switch (random.nextInt(3)) {
            case 0:
                result1.setText(String.valueOf(minimum));
                result2.setText(String.valueOf(num1 ));
                result3.setText(String.valueOf(num2 ));
                break;
            case 1:
                result2.setText(String.valueOf(minimum));
                result1.setText(String.valueOf(num1));
                result3.setText(String.valueOf(num2));
                break;
            case 2:
                result3.setText(String.valueOf(minimum));
                result2.setText(String.valueOf(num1));
                result1.setText(String.valueOf(num2));
                break;
            }
    }





}

}
4

3 回答 3

4

它可以通过创建HashSet以保留已经生成的值来解决。例如:

Set<Integer> used = new HashSet<Integer>();

// wrap this code-block in some method...
Integer num;
do {
   num = random.nextInt(10);
   if (!used.contains(num)) {
      used.add(num);
      break;
   }
} while(used.size() < 10);
于 2013-01-09T20:51:09.090 回答
2

我会做类似的事情:

num1 = random.nextInt(10) ;
num2  =( num1 + random.nextInt(10-1)+1) % 10 ;
num3 = random.nextInt(10) ;
while(num3==num1 || num3==num2)
    num3 = random.nextInt(10) ;
于 2013-01-09T20:51:34.520 回答
0

这是给你的伪代码:

int numbers[total_numbers]=-1;

for (j=0:total_numbers)
{
  flag=false;
  while (flag=false)
  {
     temp=random();
     flag=true;
     for (i=0:total_numbers) check if temp == numbers[i] then flag=false;
  }
  numbers[j]=temp;
}
于 2013-01-09T20:49:45.317 回答