By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,654 Members | 1,517 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,654 IT Pros & Developers. It's quick & easy.

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

P: 5
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}
Apr 3 '13 #1
Share this Question
Share on Google+
5 Replies


Rabbit
Expert Mod 10K+
P: 12,421
You're missing a combination, {0,2,3,5}. What have you tried?
Apr 3 '13 #2

P: 5
yeah i know that the possible number of combinations are 2 digits 3 digits 4 digits

i need to create a method ..
Apr 3 '13 #3

Rabbit
Expert Mod 10K+
P: 12,421
Yes, I know you have to create a method, but what have you tried so far?
Apr 3 '13 #4

P: 5
Expand|Select|Wrap|Line Numbers
  1. public class CombinationApp {
  2.     public static void main(String[] args) {
  3.         int[] numberlist = {1,2,3,4,5,6,7,8,9,10};
  4.         twoCombination(numberlist);
  5. }
  6.     public static int twoCombination(int[] numberlist){
  7.  
  8.         try{
  9.  
  10.         for(int x = 0;x<=numberlist.length;x++){
  11.             int fnum =numberlist[x];
  12.             int snum =numberlist[x + 1];
  13.             int sum = fnum  + snum ;
  14.             if(sum == 10){
  15.                System.out.println("{"+fnum+" , "+ snum +"}");
  16.  
  17.             }
  18.  
  19.  
  20.  
  21.  
  22.         }
  23.         }catch(ArrayIndexOutOfBoundsException e){
  24.  
  25.         }
  26.  
  27.  
  28.             return 0;
  29.         }
  30.  
  31.  
  32.  
  33.  
  34.  
  35. }
Apr 3 '13 #5

Rabbit
Expert Mod 10K+
P: 12,421
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.
Apr 3 '13 #6

Post your reply

Sign in to post your reply or Sign up for a free account.