如何从给定范围内选择随机值 [英] How to select random values from a given range

查看:30
本文介绍了如何从给定范围内选择随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 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.

这篇关于如何从给定范围内选择随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆