Java/ 数字数组中任意两个值的总和
Java/ Sum of any two values in an array of numbers
我有一个任务:
编写代码,其中包含一个 valuesTable 数组和来自整数的 givenNumber。该方法将列出这样的组合的数量,即任意两个的总和
数组中的元素等于存储在 givenNumber.
中的数字
我是否应该创建另一个数组来存储任意两个元素的总和?
什么样的方法用于获取数组中任意两个元素的总和?
如何列出组合数?
非常感谢您的帮助,这是我 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];
}
}
Should I make another array to storage sum of any two elements?
如果只需要提供与给定数量相等的对数,则不需要数组,简单的 if
语句允许检查条件并递增计数器(并打印对,如果需要):
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?
两个嵌套循环:
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
//...
}
}
How list the number of combinations?
可能对的总数是通过从 n - 1 到 1 递减级数的公式计算的:S = n * (n - 1) / 2
,因此对于 n = 5,它是 5 * 4 / 2 = 10
。
最内层循环简单统计匹配对数
我有一个任务: 编写代码,其中包含一个 valuesTable 数组和来自整数的 givenNumber。该方法将列出这样的组合的数量,即任意两个的总和 数组中的元素等于存储在 givenNumber.
中的数字我是否应该创建另一个数组来存储任意两个元素的总和? 什么样的方法用于获取数组中任意两个元素的总和? 如何列出组合数?
非常感谢您的帮助,这是我 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];
}
}
Should I make another array to storage sum of any two elements?
如果只需要提供与给定数量相等的对数,则不需要数组,简单的 if
语句允许检查条件并递增计数器(并打印对,如果需要):
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?
两个嵌套循环:
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
//...
}
}
How list the number of combinations?
可能对的总数是通过从 n - 1 到 1 递减级数的公式计算的:S = n * (n - 1) / 2
,因此对于 n = 5,它是 5 * 4 / 2 = 10
。
最内层循环简单统计匹配对数