Get a random number focused on center

后端 未结 20 2985
离开以前
离开以前 2020-12-12 09:28

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be main

20条回答
  •  失恋的感觉
    2020-12-12 09:51

    You can use a helper random number to whether generate random numbers in 40-60 or 1-100:

    // 90% of random numbers should be between 40 to 60.
    var weight_percentage = 90;
    
    var focuse_on_center = ( (Math.random() * 100) < weight_percentage );
    
    if(focuse_on_center)
    {
    	// generate a random number within the 40-60 range.
    	alert (40 + Math.random() * 20 + 1);
    }
    else
    {
    	// generate a random number within the 1-100 range.
    	alert (Math.random() * 100 + 1);
    }

提交回复
热议问题