简体   繁体   English

在数组中添加n个整数以获得Java中的目标数字?

[英]Add n number of integers in array to get a target number in Java?

An array is taken as input from the user. 数组作为用户的输入。 The array contains integers. 该数组包含整数。 Add some, all, or maybe just one is enough, to get a sum as close to 100 as possible. 加一些,全部或仅一个就足够了,以使总和尽可能接近100。

  • The array can contain 1-100 integers 数组可以包含1-100个整数
  • Each integer in the array has the value between 1-100, some could be the same. 数组中的每个整数的值都在1到100之间,有些可能相同。 The come in random order in the array 数组中的随机顺序出现
  • there is no limit how many that should be added in order to get as close to 100 as possible 没有限制应该添加多少才能使尽可能接近100
  • If several combinations are possible or give equal answers are equally close to 100, as 99 and 101, the highest should be chosen. 如果有几种组合是可能的,或者给出相等的答案,则它们的等值接近100,例如99和101,应选择最高的。

My problem is that I really don´t know how to work the loops. 我的问题是我真的不知道如何处理循环。 I have tried nestling two, but I find it tricky not to know how many integers in the array that might be needed for the calculation. 我已经尝试过嵌套两个,但是我不知道计算数组可能需要多少个整数,这很棘手。

My loops so far loops each integer: 到目前为止,我的循环会循环每个整数:

//looping over all integers in the array
for (int i = 0; i < myArray.length; i++) {
    //check already here if it is close to 100?
    //compare the integer above to the next
    for (int j = i + 1; nextWeight < myArray.length; j++) {
        //the results should be saved temporary to comparision to new sums
    }
}

I know it is not much and I know it could somehow involve dynamic programming. 我知道这并不多,而且我知道它可能以某种方式涉及动态编程。

Does anyone have any idea that could help me on the way? 有没有人对我有帮助?

By my interpretation of your question, your biggest problem lies within your algorithm. 根据我对您问题的解释,您最大的问题就在于算法。 You should first decide on an algorithm, then go to the coding. 您应该首先确定算法,然后再进行编码。 If I wanted to do what you are asking I would sort the array first, either in ascending or descending order. 如果我想按照您的要求做,我会先对数组进行升序或降序排序。 There are many sorting algorithms. 有很多排序算法。 However, I think what you are looking at is a subset sum problem which could be solved by a recursive binary tree traversal algorithm. 但是,我认为您正在查看的是子集和问题,可以通过递归二叉树遍历算法解决。 I won't give you the code, but it would do the trick if you have time to research it. 我不会给您代码,但是如果您有时间研究它,它将可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM