I have a task: Write code that will have an array of valuesTable and givenNumber from integer. The method will list the number of such combinations that the sum of any two elements in the array equal to the number stored in givenNumber.
Should I make another array to storage sum of any two elements? What kind of method use to get the sum of any two elements in the array? How list the number of combinations?
I would be very grateful for your help, this is my first steps in Java :)
public class NumberOfCombinations {
public static void main(String[] args) {
int[] valuesTable = {1, 2, 3, 4, 5};
int givenNumber = 3;
int index=0;
int sum = 0;
int n = valuesTable.length;
for (index = 0; index < n; index )
sum = valuesTable[index] valuesTable[ index];
}
}
CodePudding user response:
Should I make another array to storage sum of any two elements?
If it is required to provide only the number of the pairs equal to the given number, array is not required, simple if
statement allows to check the condition and increment the counter (and print the pair if needed):
if (a[i] a[j] == x) {
pairs ;
System.out.println("Found a pair: " a[i] " " a[j]);
}
What kind of method use to get the sum of any two elements in the array?
Two nested loops:
for (int i = 0; i < a.length - 1; i ) {
for (int j = i 1; j < a.length; j ) {
//...
}
}
How list the number of combinations?
The total number of possible pairs is calculated by the formula of decreasing progression from n - 1 to 1: S = n * (n - 1) / 2
, so for n = 5 it is 5 * 4 / 2 = 10
.
The number of matching pairs is simply counted in the innermost loop.