如何在0-9范围内生成三个随机数而无需从Android中的arraylist重复 [英] How to generate three random numbers in range 0-9 without repeating from arraylist in android

查看:572
本文介绍了如何在0-9范围内生成三个随机数而无需从Android中的arraylist重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样存储我的号码:

ArrayList<Integer> nr=new ArrayList<Integer>();

    nr.add(0);
    nr.add(1);
    nr.add(2);
    nr.add(3);
    nr.add(4);
    nr.add(5);
    nr.add(6);
    nr.add(7);
    nr.add(8);
    nr.add(9);

    Random r1 = new Random();
    Random r2 = new Random();
    Random r3 = new Random();

   int rnd1 = r1.nextInt(nr.size());
    nr.remove(rnd1);
   int rnd2 = r2.nextInt(nr.size());
    nr.remove(rnd2);
   int rnd3 = r2.nextInt(nr.size());
    nr.remove(rnd3);

我尝试删除生成的数字,但是经过一些尝试后,它会不断重复

I try to remove the generated numbers but it keeps repeating after some tries

推荐答案

此处的想法是,您将生成一个范围为0..9的随机数.然后删除一个元素,并生成另一个范围为0..8的随机数.最后,生成第三个数字,范围是0..7.

The idea here is that you are generating a random number in the range 0..9. Then you remove one element and you generate another random number in the range 0..8. You finish with generating a third number in the range 0..7.

正确的方法是使用您生成的数字作为元素的索引.您使用带有该索引的元素:这是您的随机"数字.然后,删除该元素,以免再次使用它(在我的情况下,我使用一个操作"remove"来获取和删除该元素).

The correct way would be to use the numbers that you generated as indexes for the elements. You take an element with this index: this is your "random" number. Then you remove this element so that you couldn't take it again (in my case, I obtain and remove the element using one operation: "remove").

ArrayList<Integer> nr = new ArrayList<Integer>();

nr.add(0);
nr.add(1);
nr.add(2);
nr.add(3);
nr.add(4);
nr.add(5);
nr.add(6);
nr.add(7);
nr.add(8);
nr.add(9);

Random r = new Random();

int rndPos1 = r.nextInt(nr.size());
int rnd1 = nr.remove(rndPos1);

int rndPos2 = r.nextInt(nr.size());
int rnd2 = nr.remove(rndPos2);

int rndPos3 = r.nextInt(nr.size());
int rnd3 = nr.remove(rndPos3);

System.out.println(rnd1 + ", " + rnd2 + ", " + rnd3);

这篇关于如何在0-9范围内生成三个随机数而无需从Android中的arraylist重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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