当前位置:网站首页>Create an int type array with a length of 6. The values of the array elements are required to be between 1-30 and are assigned randomly. At the same time, the values of the required elements are diffe

Create an int type array with a length of 6. The values of the array elements are required to be between 1-30 and are assigned randomly. At the same time, the values of the required elements are diffe

2022-07-07 09:28:00 A Bai|

Create a length of 6 Of int Type of the array , The value of the array element is required to be 1-30 Between , And random assignment . At the same time, the element values are required to be different . 

requirement 1:random produce [ 0 , 1) The random double Type data , Multiply by the range to round , The range of the obtained number is [ Left interval , The right range - 1], Finally, the whole + 1 That is to say [ Left interval + 1, The right range ].

requirement 2: The method is to use while Cycle brush random numbers , This question is relatively simple .

  I tested my code several times , Not more than 1ms Of , On the whole, it is relatively fast

package p1.text;
import java.util.*;
/**
 * @author WitMoy
 * @version V1.8
 * @date : 2022-07-02 18:16
 */
public class Main {
    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        int[] ans = new int[6];
        for(int i = 0; i < 6; i++){
            ans[i] = (int)(Math.random()* 30 + 1);
            while(true){
                boolean flag = true;
                for(int j = 0; j < i; j++){
                    if(ans[i] == ans[j]){
                       flag = false;
                       break;
                    }
                }
                if(flag) break;
                ans[i] = (int)(Math.random()* 30 + 1);
            }
        }
        System.out.println(Arrays.toString(ans));
        long end = System.currentTimeMillis();
        System.out.println("\n when : " + (end - begin) + "ms");
    }
}

 

原网站

版权声明
本文为[A Bai|]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070647408450.html