M
M
MdaUZH2016-08-23 10:43:30
Android
MdaUZH, 2016-08-23 10:43:30

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);
    }

But it does not work as it should, there are still the same numbers ...
Please tell me why

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-08-23
@MdaUZH

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 question

Ask a Question

731 491 924 answers to any question