android: generate random number without repetition

后端 未结 4 2025
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 00:03

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 t

4条回答
  •  长情又很酷
    2021-01-07 00:30

    Have you tried just using Math.random()?

    Just do some casting magic and you'll be good to go:

    int index = (int)((double)prjcts.size() * Math.random());
    

    Edit:

    If you want prevent repetition, you could create a list with all the possible indices.

    int max = prjcts.size();
    List indices = new ArrayList(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 is now guaranteed to be a never-before used index of of your JSON list.

提交回复
热议问题