J2ME takes the number of randhes

xiaoxiao2021-03-06  48

Random rd; rd = rd.nextint () >>> 1% 101, this is the time as seed, and the distribution should be relatively uniform.

For SBAMDANB00 (beetle): / ************************************************** ************ * Function: Get random number * Enter parameters: above, the following * Output parameters: random results **************** ******************************************* /

Public int ramdon (int area1, int area2) {while (TRUE) {TRY {THREAD.SLEP (100);} int intetmp = new random (). nextint (); INTTMP = Math.Abs (INTTMP% Area2); if (INTTMP> = Area1 && INTTMP <= Area2) {Return INTTMP;}}}

The landlord pays attention to the upstairs, and if the number is continuously taken according to their methods, it is likely that the value will be the same in a time period, you must sleep for a while.

Explanation; Rand.nextint () is generated by INT data, with a positive and negative points. >>> 1 This is logically right, and the highest bit is filled with 0, it becomes a positive value. Of course, Math.Abs ​​() is also possible, but >>> belongs to the shift operation, the speed is fast.

For example, there is a test question: How to achieve the fastest implementation 2 3 times = 8? The answer is: 2 << 3 = 8

2. Why% 101?

The requirements of the building are 0- "100.

% 100 is 0 - "99. One number is 100, the remainder may be equal to 100? Obviously divided by 101.

3. Randomly generated int value may be negative, direct% 101 will result in negative numbers, turn the highest bit into 0 through logic right shift, is positive. Take the absolute value to call the method, the Java virtual machine is stack, new FRAME, the efficiency is too low. And there is an implicit error, that is, when you take the minimum int value, its absolute value is larger than the maximum int value, which exceeds the expression range of the int value, huh.

转载请注明原文地址:https://www.9cbs.com/read-67104.html

New Post(0)