简体   繁体   中英

Finding all possible sums of a number in an array

Say I have an array of int[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} . I want to display the array, then ask for input to pick a number and print out all possibilities to make that number from that array.

For example, Input is 10
Expected results: 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);
    }

What I tried is to call a method and pass the input value. At allSumsOfIndex I tried to do something but I can't figure out the if logic, and read online something about recursion but don't know how to implement it.

 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM