+ 3

Dividing number according to the list

In my project, I have faced the following problem: I have a double value ( for example 120.6 ) and list (for example [1, 2.5, 3.8, 5.5, 7.9, 20.6, 100, 125.5, 150.6, 200, 400, 900.8] ). I should divide 120.6 into pieces so each piece must be an element of the list (like 100 + 20.6) And pieces total count must be the fewest. If list values are not able for dividing input value, I should subtract some number from the input, that makes input able for dividing, and this reminder also must be minimum. What algorithm I should us for this situation?

24th Sep 2019, 4:07 PM
Sharofiddin
Sharofiddin - avatar
1 Respuesta
+ 1
I would loop throu the list and subtract the element from your example 120.6 and make an if to test is if the result is in your list JS: let num let list = [1, 2.5, 3.8, 5.5, 7.9, 20.6, 100, 125.5, 150.6, 200, 400, 900.8]; for(var lnum in list) { var diff = num - lnum; if(list.indexOf(diff) >= 0) { break; } } console.log(lnum + ", " + diff);
18th Nov 2019, 9:07 PM
Nico Ruder
Nico Ruder - avatar