android – 生成随机数,不重复
任何人都可以告诉我如何生成随机数,没有重复的例子
random(10)应该(可能)返回3,4,2,1,7,6,5,8,9,10而不重复
谢谢
我建议将数字添加到ArrayList
,然后使用Collections.shuffle()
随机化他们的顺序。 像这样的东西:
ArrayList number = new ArrayList (); for (int i = 1; i <= 10; ++i) number.add(i); Collections.shuffle(number);
制作生成的数字列表,当您新生成的数字已在此列表中时,您将创建一个新的随机数。
Random rng = new Random(); // Ideally just create one instance globally List generated = new ArrayList (); for (int i = 0; i < numbersNeeded; i++) { while(true) { Integer next = rng.nextInt(max) + 1; if (!generated.contains(next)) { // Done for this iteration generated.add(next); break; } } }
我的两分钱
public Collection getRandomSubset(int max,int count){ if(count > max){ throw new IllegalArgumentException(); } ArrayList list = new ArrayList (); for(int i = 0 ; i < count ;i++){ list.add(i); } Collections.shuffle(list); return list.subList(0, count); }
如果只有少数数字,少于100,我认为我的解决方案可以创建一个布尔数组,一旦得到一个数字,将数组的位置设置为true。 我不认为需要很长时间才能显示所有数字。 希望能帮助到你!
干杯!