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

2022-01-24 00:00:00 random range android java

我正在尝试创建一个 android 应用程序,它将在给定范围内生成随机系列值(在这种情况下为整数)(但它们之间 NOT 相等)并以简单的方式显示它们文本视图

I'm trying to create an android application which will generate random series of values (integer numbers in this case) in a given range (but NOT equal between them) and display them in a simple TextView

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

每按一次按钮生成"我想随机生成5个不同的结果

Each time I press the button "Generate" I want to randomly generate 5 different results

每个生成"的示例:

  • 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<Integer> mySet = new HashSet<Integer>();
    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(<a seed number>);

Set<Integer> mySet = new HashSet<Integer>();
while (mySet.size() < 5) {
   int idx = r.nextInt(<length of your data>)
   mySet.add(data[idx]);
}

数据包含您的范围数字.

data contains your range numbers.

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

在您的 TextView 中设置此文本.

set this text in your TextView.

相关文章