The Java interview algorithm randomly generates an array with a length of 20, and enters the numbers that add up to 10, and there are no repeated numbers

 Randomly generate an array with a length of 20, enter the numbers that add up to 10, and there will be no repeated numbers

Randomly generate an array code of 20 digits 1-10 

 int[] arr =new int[20] ;
        for (int i=0; i<20; i++){
            int arr2=(int)(Math.random()*10);
            arr[i] = arr2;
        }
        System.out.println("随机20数组为:"+ Arrays.toString(arr));

The output value adds up to a number equal to 10, and no repeated elements appear


 List list = new ArrayList();
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i] + arr[j] == 10 && i != j && arr[i] != arr[j]) {
                    if (!list.contains(arr[i]) || !list.contains(arr[j])) { //contains判断集合中是否包含指定的元素
                        list.add(arr[i]); //add将元素存入list中
                        list.add(arr[j]);
                        System.out.println(arr[i] + "+" + arr[j] + "=10");
                    }
                }
            }
        }

result

 

Guess you like

Origin blog.csdn.net/qq_57484285/article/details/128957172