为链接列表插入生成2个范围之间的随机数

时间:2020-08-02 00:05:56

标签: java singly-linked-list

嗨,我正在尝试生成介于(-30,-10)和(10,30)的2组范围之间的随机数,以存储在LinkedList Node中。如果生成的数字为负数,则在列表的“头部”插入此元素和下一个元素(无论其值如何)。如果生成的数字为正,则此元素和下一个元素将存储在“ tail”中。这就是我到目前为止所拥有的。

public class CAO_QUANG_JUIN_P4 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    //////////////////////////bloc1:Decleration des variables//////////////////////////

    //Create a EVEN N variable between 10 and 30
    
    int N = (int)(Math.random()*20)+10;
    N = (N*2)%30;
    //Create a simple linkedlist with N nodes
    LC e1 = new LC();
    LC tete = null;
    while(N!=0) {
        if(e1==null) {
            e1 = new LC();
            tete = e1;
            e1.data = N;
            
        }
        else {
            e1.suiv = new LC();
            e1.suiv.data = N;
            e1 = e1.suiv;
        }
        N = (int)(Math.random()*20)+10;
        int M = (int)(Math.random()*-20)-10;
    }

2 个答案:

答案 0 :(得分:3)

您有两个选择:

  1. 首先“翻转硬币”来确定是正数还是负数,然后根据硬币翻转生成-10 / -30或10/30。
  2. 生成一个[0,40]范围内的随机数,并将它们映射到您实际的期望范围内。

请注意,如果您想要均匀的随机分布,则如果两个范围的大小不相等,则#1会出现问题。

另外请注意,Math.random() * 20是错误的。

从根本上讲,通过数学证明:

  1. Java中的double具有64位。这意味着它最多可以表示2 ^ 64个数字。那是很多数字,但不是无限数量。
  2. ...,其中只有一些数字介于0(含)和1(不含)之间。假设是其中的1000005。
  3. 鉴于它们正好是10000005,并且这些10000005数字中的每一个倒数都会“映射”到您的一个数字,其总“范围”为20(或40,无关紧要), ,40不能完全适合10000005。
  4. 因此,我证明了某些数字会比其他数字更多地出现,而您的结果并不是真正的随机。 QED。

解决方案是创建一个Random实例并使用其 IS 真正均匀分布的.nextInt(20)方法。

投币法

Random r = new Random(); // make one instance, once, in your app.
boolean goNegative = r.nextBoolean();
int nr = (goNegative ? -1 : +1) * (10 + r.nextInt(20));
// note, like in your example, 10 is possible,
//but 30 cannot be hit. Make it r.nextInt(21)
//instead if it needs to be.

映射器方法

Random r = new Random(); // make one instance, once, in your app.
int nr = r.nextInt(40);
if (nr < 20) nr -= 29; // all numbers from -29 to -10, inclusive, covered.
else nr -= 10; // covers 10-29 inclusive.

答案 1 :(得分:2)

尝试以下操作:

Random r = new Random();
// the following generates a number between 0 and 20 inclusive and adds 10 to it
int a = r.nextInt(21)+10; // between 10 and 30 inclusive

// the following does the same but changes the sign.
int b = -(r.nextInt(21)+10); // between -10 and -30 inclusive

For the negative one you could also do this.
b = -30+r.nextInt(21);

因此,如果您想从两个集合中随机选择一个,则可以执行以下操作:

int n = nextInt(2) == 0 ? -30+r.nextInt(21) : r.nextInt(21)+10;