Finding closest sum of numbers to a given number

后端 未结 5 1724
我在风中等你
我在风中等你 2021-01-25 09:11

Say I have a list [1,2,3,4,5,6,7] and I would like to find the closest sum of numbers to a given number. Sorry for the crappy explanation but here\'s an example:

Say I h

5条回答
  •  感情败类
    2021-01-25 09:35

    From what I understood from your question, I made this snippet. I assumed you did not wanted to have the same digit twice (e.g 14 => 7 + 7).

    It is working with your examples.

    var arr = [1, 2, 3, 4, 5, 6, 7];
    
    var a = 0, b = 0;
    var nb = 14;
    
    for(var i in arr) {
      for(var j in arr) {
        if(i != j) {
          var tmp = arr[i] + arr[j];
          if(tmp <= nb && tmp > a + b) {
            a = arr[i];
            b = arr[j];
          }
        }
      }
    }
    
    document.write("Closest to " + nb + " => " + a + " + " + b);

提交回复
热议问题