在数组中找到一个数字的所有可能的和

时间:2019-12-19 19:02:15

标签: java arrays sorting

说我有一个int[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}数组。我想显示该数组,然后要求输入以选择一个数字并打印出从该数组中获得该数字的所有可能性。

例如,输入为10
预期结果:1 + 9、2 + 8 ... 1 + 2 + 7、1 + 3 + 6 ... 1 + 2 + 3 + 5 ...

public class Detyra35 {

    private int[] unsortedNumbers;

    public Detyra35(int[] unsortedNumbers) {
        this.unsortedNumbers = unsortedNumbers;
    }

    public int[] sorted() {
        int[] sortedNumbers = Arrays.copyOf(this.unsortedNumbers, this.unsortedNumbers.length);
        Arrays.sort(sortedNumbers);
        return sortedNumbers;
    }


    public void allSumsOfIndex(int index, int a){
        Detyra35 recursion= new Detyra35(unsortedNumbers);
        for (int i=a; i<index; i++){
            if(unsortedNumbers[i]+(unsortedNumbers[i+1])==index){
                System.out.println(unsortedNumbers[i]+" + " +unsortedNumbers[i+1]+" = "+index);
            }
            recursion.allSumsOfIndex(index,a+1);
        }
    }

    public class Main {
    public static void main(String[] args) {
        Scanner scanner= new Scanner(System.in);
        //Pass the array into the constructor
        int[] oneToTenArray= {1,2,3,4,5,6,7,8,9,10};
        Detyra35 oneToTen= new Detyra35(oneToTenArray);
        //sort the array and print it so can pick the input
        oneToTen.sorted();
        System.out.println(Arrays.toString(oneToTenArray));
        System.out.println("Enter the number you want to check all possibilities of sum");
        int choice= scanner.nextInt();
        //call the method to check all sums 0
        oneToTen.allSumsOfIndex(choice,0);
    }

我尝试的是调用方法并传递输入值。在allSumsOfIndex,我尝试做一些事情,但我无法弄清楚if逻辑,无法在线阅读有关递归的知识,但不知道如何实现。

1 个答案:

答案 0 :(得分:0)

function sums(arr, sum) {
    let pairs = [];
    let numList = [];

    for (let i = 0; i < arr.length; i++) {
        let currNum = arr[i];
        let diff = sum - currNum;
        if (numList.includes(diff)) {
            pairs.push([currNum, diff]);
        }
        numList.push(currNum);
    }
    return pairs;

}
let num = 10;
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(sums(arr,num));