math.random() follows which algorithms

前端 未结 5 1552
盖世英雄少女心
盖世英雄少女心 2021-01-03 03:47

Am using math.random() method to generate random numbers. but i had a doubt about that method. math.random() is which algorithms will fallow to generate random

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 04:26

    The simplest way to do what you are trying to do is

    String[] words = ...
    Collections.shuffle(Arrays.asList(words));
    

    You are right that generating a random double and then turning it into a small integer is not efficient. Fortunately Random has a method for this.

    Random rand = new Random();
    for (int i = words.length - 1; i > 0; i--) {
         int sd = rand.nextInt(i+1); // random number between 0 and i inclusive
    
         String t = words[r];
         words[r] = words[i];
         words[i] = t;
    }
    

提交回复
热议问题