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

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

问题描述

我想创建一个Android应用程序,这将在一定范围内产生随机序列值(在这种情况下,整数)(但不会等于他们之间),并在一个简单的显示出来的TextView

比方说,我们有一系列的 R = [1,2,3,4,5,6,7,8,9,10,11,12,13]

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

示例为每一个生成:

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

编辑(现在的工作),感谢所有帮助!

 公共类随机延伸活动{


静态最终整数[]数据=新的整数[] {
    1,2,3,4,5,6,7,8
    };


@覆盖
公共无效的onCreate(包冰柱){
    super.onCreate(冰柱);
    的setContentView(R.layout.main);

    随机R =新的随机();

    设置<整数GT; MYSET =新的HashSet<整数GT;();
    而(mySet.size()小于5){
       INT IDX = r.nextInt(data.length);
       mySet.add(数据[IDX]);
    }

    字符串文本=;
    对于(整数i:MYSET){
       文=文+ I +,;
    }
       TextView的数=(TextView中)findViewById(R.id.shownumbers);
       Numbers.setText(文本);
  }
}
 

解决方案

 随机R =新的随机(小于一个种子数>);

设置<整数GT; MYSET =新的HashSet<整数GT;();
而(mySet.size()小于5){
   INT IDX = r.nextInt(<您的数据&GT的长度)
   mySet.add(数据[IDX]);
}
 

数据中包含的范围内的数字。

 字符串文本=;
对于(整数i:MYSET){
   文=文+ I +,;
}
 

在你的TextView中设置该文本。

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

Let's say we have the range R = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

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

Example for each "Generate":

  • 4, 9, 2, 12, 10
  • 5, 1, 6, 8, 13
  • 10, 4, 6, 8, 2
  • etc...

EDIT (works now) Thanks for all the help!

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 + ", "; 
}

set this text in your TextView.

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

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