Finding closest sum of numbers to a given number

后端 未结 5 1814
我在风中等你
我在风中等你 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:49

    I have a little bit long winded solution to the problem just so it is easier to see what is done.

    The main benefits with solution below:

    • The second loop will not start from beginning of the array again. What I mean that instead of having loop_boundary for second loop as 0 as you normally would, here it starts from next index. This helps if your numbers array is long. However, if it as short as in example, the impact in performance is minimal. Decreasing first loop's boundary by one will prevent errors from happening.
    • Works even when the wanted number is 1 or negative numbers.

    Fiddle:

    JSFiddle

    The code:

    var numbers = [1,2,3,4,5,6,7];
    var wanted_number = 1;
    var closest_range, closest1, closest2 = null;
    
    var loop1_boundary = numbers.length-1;
    for(var i=0; i' );
    
            if(Math.abs(range) < Math.abs(closest_range) || closest_range == null ) {
                closest_range = range;
                closest1 = number1;
                closest2 = number2;
            }
    
        }
    
        if(range==0){
            break;
        }
    }
    
    document.write( 'closest to given number was '+closest1+' and '+closest2+'. The range from wanted number is '+closest_range );
    

提交回复
热议问题