我试图从列表中找到所有可能的总和。 该列表由用户输入的整数组成,输入数量由用户决定(参见代码)。 我想要的是在没有目标的情况下检查所有可能的总和。 我不想要目标的原因是因为程序随后被调整以选择最接近1000的这些总和中的一个。 因此,如果我选择1000作为目标,我将无法说出1001。
来自用户的示例输入:
5 // user chose 5 numbers.
500,400,300,50,60 // numbers chosen by user.
输出将是:
1010 // because 500+400+60+50= 1010 and closest to 1000.
下一个例子可能是:
3 // user chose 3 numbers.
1,2,3 // numbers chosen by user.
输出将是:
6 // because 1+2+3 = 6.
回到我原来的问题,这是怎么做到的?每次我搜索一下所有可能的整数列表"或类似于我得到一个目标,它在这个例子中起作用。
public static void main(String[] args) throws Exception {
int bästaVikt;
int räknare = 0;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> mylist = new ArrayList<Integer>();
int s;
s = sc.nextInt();
int ans = 0;
for(int i = 1; i <= s; i++) {
mylist.add(sc.nextInt());
}
for(int i = 0; i < mylist.size(); i++) {
Collections.sort(mylist);
System.out.print(mylist.get(i));
System.out.print(" ");
}
}
答案 0 :(得分:0)
半实际代码半伪代码,希望它有所帮助。
input // the array that holds all numbers than the user input
int n = input.length();
ArrayList<Integer> combinations = new ArrayList<Integer>();
int totalSum = input.sum(); // sum of all the values the user input
ArrayList<Integer> allSums = new ArrayList<Ingeter>();
for(int i = 0; i < n; i++){
combinations = combine(i) // find all possible combinations of i integers in the input array; you can surely find code for retrieving combinations in another thread
foreach combination in combinations{
allSums.add(totalSum - combination.sum())
}
combinations = new ArrayList<Integer>(); // clear the combinations arraylist
}
return allSums; //all possible sums
minDistanceToNumber = absolute(allSums.get(0) - 1000); // define a function "int absolute(int value)" which will multiply value by -1 if it is less than 0 and return it or just return it if it is bigger than 0
minNumber = allSums.get(0); // this will hold the number which has the minimum distance to 1000, as in the example above
for each sum in allSums
if(absolute(sum - 1000) < minDistanceToNumber){
minDistanceToNumber = absolute(sum - 1000);
minNumber = sum;
}
}
return minNumber;