Bug in random numbers in Android

后端 未结 3 1946
我在风中等你
我在风中等你 2021-01-26 03:14
TreeSet myNumbers = new TreeSet();
Random randGen = new Random();

for (int i = 1; i <= 16; i++) {
    // number generation here
    int randNum = randGen.nextInt(16          


        
3条回答
  •  野性不改
    2021-01-26 03:49

    It's not a big issue, if you are working in the range 1-16, but your code results in rejection of some randomly drawn numbers, if they have already been picked before. In your solution, the expected value of nextInt() calls is proportional to n log(n), where n is the number of total elements you want to shuffle (16 in your case) – and the actual values can be much higher for a single run. You might consider using a more efficient implementation.

    A solution which always uses only n calls:

    ArrayList originalNumbers = new ArrayList();
    Random randGen = new Random();
    int max = 16;
    for (int i = 1; i <= max; i++) {
        // initializing ordered list so it becomes 1, 2, ..., max
        originalNumbers.add(i);
    }
    for (int i = max; i >= 1; i--) {
        // picking a random number from the ordered list, and swapping it
        // with the last unpicked element which is placed closer to the
        // end of list, where the already picked numbers are stored
        int randNum = randGen.nextInt(i);
        Collections.swap(originalNumbers, i - 1, randNum);
        Toast.makeText(getApplicationContext(), "" + originalNumbers[i - 1], 100).show();
    }
    

提交回复
热议问题