简体   繁体   中英

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.

  • The array can contain 1-100 integers
  • Each integer in the array has the value between 1-100, some could be the same. 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
  • If several combinations are possible or give equal answers are equally close to 100, as 99 and 101, the highest should be chosen.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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