Answer the question
In order to leave comments, you need to log in
How to generate random non-same numbers?
Hello everyone)
We need a random number generator, but so that the numbers do not repeat ..
I do this:
Random random = new Random();
..
ArrayList<Integer> rtn = getFalseRandom(5);
for(int i=0;i<rtn.size();i++){
Log.d("TAG", "LOL "+rtn.get(i).toString());
}
...
public ArrayList<Integer> getFalseRandom(int count){
ArrayList<Integer> rtn = new ArrayList<Integer>();
for(int i=0;i<3;i++) { // 3 потому что нужно 3 числа
int n = getContainsRandom(rtn, count)+1;
rtn.add(n);
}
return rtn;
}
public int getContainsRandom(ArrayList<Integer> list, int count){
int n = random.nextInt(count);
if(!list.contains(n)) {
return n;
}
return getContainsRandom(list,count);
}
Answer the question
In order to leave comments, you need to log in
At you linear complexity (search in an array) plus a recursion on such simple operation.
Set<Integer> used = new HashSet<>();
...
public int getContainsRandom( Set<Integer> used ){
int i;
do{
i = random.nextInt(...);
while(used.contains(i));
used.put(i);
return i;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question