机器人:生成随机数字,没有重复 [英] android: generate random number without repetition
问题描述
任何人可以帮助我在做的方法来生成随机数字,没有重复的机器人?
的最大数量为: prjcts.size();
这是我的JSON数组。而返回值应该是整数。
can anybody help me in making a method to generate random number without repetition in Android?
The maximum number is: prjcts.size();
it's my JSON Array. And the return value should be in integer.
我已经有是:
INT I =(INT)(prjcts.size()*的Math.random());
我铸造的方法3次,因为我需要3个随机生成的数字。它的工作原理,但我不知道如何使它不重复。所以,这些3个数字将不彼此之间是相同的。
What I've already had is:
int i = (int)(prjcts.size() * Math.random());
I casted the method 3 times, because I need 3 random generated numbers. It works, but I don't know how to make it without repetition. So those 3 numbers won't be the same between each other.
感谢您
推荐答案
您是否尝试过只用的的Math.random()?
只是做一些铸造魔法,你会好到哪里去:
Just do some casting magic and you'll be good to go:
int index = (int)((double)prjcts.size() * Math.random());
编辑:
如果你想prevent重复,您可以创建的所有可能的索引列表。
If you want prevent repetition, you could create a list with all the possible indices.
int max = prjcts.size();
List<int> indices = new ArrayList<int>(max);
for(int c = 0; c < max; ++c)
{
indices.add(c);
}
然后你想一个随机指数每一次,刚刚从列表中选择一个随机的项目,从列表中删除后,它的时候,你就大功告成了。
Then each time you want a random index, just pick a random item from the list, removing it after from the list when you're done
int arrIndex = (int)((double)indices.size() * Math.random());
int randomIndex = indices.get(arrIndex);
indices.remove(arrIndex);
randomIndex
现在保证是你的JSON列表中的一个以前从未使用的索引。
randomIndex
is now guaranteed to be a never-before used index of of your JSON list.
这篇关于机器人:生成随机数字,没有重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!