I have an array that has multiple numbers in it. I want the function to return another array of maximum 3 numbers from the array that, when added together, equals another number.
It can be 1 or 2 numbers too, but the first number must be the highest possible.
e.g.:
var array = [1,2,3,4,5,6,7,8,9,10];
var number: 25;
desired output: [10,10,5]
Or
var array = [1,2,3,4,5,6,7,8,9,10];
var number: 11;
desired output: [10,1]
Or
var array = [1,2,3,4,5,6,7,8,9,10];
var number: 5;
desired output: [5]
As you will probably see, i am building a small dart application that calculates your points. this is the last part where i need to show which combination of darts can get you to reach exactly 0 regardless of how many darts i have thrown.
I can loop through my numbers and get them in an array but as soon as the combination needs to have a smaller number before another one, it cant compute. Here's the code:
// the numbers to add
var finishingNumbers = [60, 57, 54, 51, 50, 48, 45, 42, 40, 39, 38, 36, 34, 33, 32, 30, 28, 27, 26, 25, 24, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
// The number
var output = 167;
// The variable for the end result
var dartsToFinishArr = [];
// Call my function
checkArray();
function checkArray() {
for (var j = 0; j < finishingNumbers.length; j++) {
var dartsToFinishArrTotal = 0;
if (dartsToFinishArr.length > 0) {
for (n = 0; n < dartsToFinishArr.length; n++) {
dartsToFinishArrTotal += dartsToFinishArr[n];
}
}
if (output <= 180) {
if (finishingNumbers[j] + dartsToFinishArrTotal == +($(".matchContainer .matchPlayerContainer .player.playerTurn .playerScore .value").text()) && dartsToFinishArr.length < 3) {
dartsToFinishArr.push(finishingNumbers[j]);
return;
} else if (finishingNumbers[j] + dartsToFinishArrTotal < output && dartsToFinishArr.length < 3) {
dartsToFinishArr.push(finishingNumbers[j]);
checkArray();
return;
} else if (dartsToFinishArrTotal != output) {
return;
}
}
}
}
this should give me:
var dartsToFinishArr = [60, 57, 50]
but it doesnt
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)