Check whether there is a combination of numbers that meets the conditions

Topic information

Enter a set of numbers, separated by spaces, to determine whether the entered numbers can meet A=B+2C, and each element can only be used once at most. If there is a combination of numbers that meet the conditions, output the three numbers A, B, and C in turn, separated by spaces; if there is no combination that meets the conditions, output 0.

For example: input 2 3 5 7 output 7 3 2

coding

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class CheckNumCouple {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String input;
		while ((input = br.readLine()) != null) {
			String[] numArrStr = input.split(" ");
			checkNumsCouple(numArrStr);
		}
	}
	
	/**
	 * 检查是否存在满足条件的数字组合
	 * @param arrs 数组
	 */
	public static void checkNumsCouple(String[] arrs) {
		// 将字符数组转换为Integer数组
		Integer[] arr = new Integer[arrs.length];
		for (int i=0; i<arrs.length; i++) {
			arr[i] = Integer.valueOf(arrs[i]);
		}
		
		// 让数组降序排列
		// 通过下面的循环,此处排序可以不要
		Arrays.sort(arr, new Comparator<Integer>(){
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
		
		// 定义标识,是否有满足条件数字组合
		// 0 无;1或其它值 有
		int index = 0;
		
		// 循环数组,让等式相等且3个元素的位置不相等
		for (int i=0; i<arr.length; i++) {
			for (int j=0; j<arr.length; j++) {
				for (int k=0; k<arr.length; k++) {
					if ((arr[i] == arr[j] + 2*arr[k]) && (i!=j && i!=k && j!=k)) {
						index++;
						System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
					}
				}
			}
		}
		
		// 无满足条件的数字
		if (index == 0) {
			System.out.println(0);
		}
	}
}

Above code

Enter 2 3 4 5 7

Output 7 3 2

Enter 2 4 0

Output 4 0 2

Enter 1 2 3

Output 0

Guess you like

Origin blog.csdn.net/magi1201/article/details/114648747