method to returns all possible number combinations and their sum is equal to a number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • adri00713
    New Member
    • Apr 2013
    • 5

    method to returns all possible number combinations and their sum is equal to a number

    Given the list of a maximum of 10 numbers, where all numbers
    are different in the list create a method that will
    return all possible combinations in each combination the
    of the numbers should be equal to 10.

    example: input number list {0,2,3,5,10}

    output is

    {2,3,5} {0,10}
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You're missing a combination, {0,2,3,5}. What have you tried?

    Comment

    • adri00713
      New Member
      • Apr 2013
      • 5

      #3
      yeah i know that the possible number of combinations are 2 digits 3 digits 4 digits

      i need to create a method ..
      Last edited by Niheel; Apr 3 '13, 06:04 PM. Reason: unnecessary multiple posts, please try to respond in one complete post vs posting bits in multiple post.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Yes, I know you have to create a method, but what have you tried so far?

        Comment

        • adri00713
          New Member
          • Apr 2013
          • 5

          #5
          Code:
          public class CombinationApp {
              public static void main(String[] args) {
                  int[] numberlist = {1,2,3,4,5,6,7,8,9,10};
                  twoCombination(numberlist);
          }
              public static int twoCombination(int[] numberlist){
                  
                  try{
                      
                  for(int x = 0;x<=numberlist.length;x++){
                      int fnum =numberlist[x];
                      int snum =numberlist[x + 1];
                      int sum = fnum  + snum ;
                      if(sum == 10){
                         System.out.println("{"+fnum+" , "+ snum +"}");
                        
                      }
                      
                     
                      
                     
                  }
                  }catch(ArrayIndexOutOfBoundsException e){
                      
                  }
                  
                  
                      return 0;
                  }
          
           
              
              
              
          }
          Last edited by Niheel; Apr 3 '13, 06:37 PM. Reason: use code tags

          Comment

          • Rabbit
            Recognized Expert MVP
            • Jan 2007
            • 12517

            #6
            All that does it add two numbers to see if the sum is 10. What you need to do is loop through every combination of numbers to see if it adds up to 10. To that end you will need to use at least 2 loops. One nested in the other.

            Comment

            Working...