java - Random number generator generates duplicates -
framework: java
public static list<integer> buttonidlist = new arraylist(); public void mymainmethod() { for(integer = 0; < 11; i++) { int randombuttonid = getuniqueidnumber(); } } private static integer getuniqueidnumber() { random ran = new random(); int randombuttonid = ran.nextint(20) + 1; if(buttonidlist.contains(randombuttonid)) { getuniqueidnumber(); } else { buttonidlist.add(randombuttonid); } return randombuttonid; }
when code encounters duplicate, calls (recursively) , in second try if number unique return statement returns mymainmethod or getuniqueidnumber?
where should return statement placed?
you should return result of recursive call:
private static integer getuniqueidnumber() { random ran = new random(); int randombuttonid = ran.nextint(20) + 1; if(buttonidlist.contains(randombuttonid)) { return getuniqueidnumber(); } else { buttonidlist.add(randombuttonid); } return randombuttonid; }
p.s., better make random ran
static
variable instead of creating new random
instance in each recursive call.
private static random ran = new random(); private static integer getuniqueidnumber() { int randombuttonid = ran.nextint(20) + 1; if(buttonidlist.contains(randombuttonid)) { return getuniqueidnumber(); } else { buttonidlist.add(randombuttonid); return randombuttonid; } }
and might consider changing buttonidlist
hashset
(or linkedhashset
if care insertion order) in order make search existing number more efficient.
wiki
Comments
Post a Comment