-1

How can I change my code to find all possible number combination where addition of number is equal to some input number.

Example data

We have array [1,4,6,8,9,12,17,19,21,28,45,67,.....,n]and input number 29

Expect result is (Sum of multiple value from array that equal to x) [1,28] [8,21] [1,9,19] ....

My current code is

int [] number = new int[]{1,5,8,12,15,18,20,24,28,30};
    int expectValue = 25;

    for (int i = 0; i < number.length-1 ;i++){
        for (int j = i+1; j < number.length; j++){
            if(number[i] + number[j] == expectValue){
                System.out.println("["+number[i]+","+number[j]+"]");
            }
        }
    }

Result

[1,24][5,20]
ZDK
  • 91
  • 2
  • 11
  • 1
    `How can I create java or kotlin code for solve this issue?` By start making it. – Gatusko Sep 10 '19 at 14:25
  • @Gatusko Thank you for your reply. Yeah i tried but not get solution yet. – ZDK Sep 10 '19 at 14:37
  • @LiNgKung show you attempt. That's what he meant. Pure coding requests are off-topic on SO. We can help you write you code but not write it for you. – Yoshikage Kira Sep 10 '19 at 14:52
  • I believe you are trying to write sudoko. You should check this out [Algorithm for solving Sudoku](https://stackoverflow.com/questions/1697334/algorithm-for-solving-sudoku) – Yoshikage Kira Sep 10 '19 at 14:59
  • @Goion Hi, I updated my code on topic. – ZDK Sep 10 '19 at 15:19
  • Possible duplicate of [Finding all possible combinations of numbers to reach a given sum](https://stackoverflow.com/questions/4632322/finding-all-possible-combinations-of-numbers-to-reach-a-given-sum) – Yoshikage Kira Sep 10 '19 at 16:12

1 Answers1

0

Here is some basic code to get you started. It only covers the case where two numbers sum to the target value.

 public static void main(String args[])
    {
        int[] precursors = {10,20,30,1,2,3,4,5,6,7,8};
        Arrays.sort(precursors);
        int target = 12;

        for (int i = 0; i < precursors.length; i++)
        {
            for(int j = 0; j < precursors.length; j++)
            {
                if (precursors[i] >= target)
                {
                break;
                }
                else if (precursors[i] + precursors[j] == target){
                    System.out.println("[" + precursors[i] + "," + precursors[j]+ "]");
                }
            }
        }


    }
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35