-
-
Save kidker/aefa0f4f775df4cf8778 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Напишите функцию, которая из произвольного входящего массива выберет все комбинации чисел, сумма которых будет равняться 10 | |
* | |
* @see http://company.yandex.ru/job/vacancies/dev_int_yaservices.xml | |
* @param {Array} ITEMS | |
* @param {Integer} target | |
* @example findCombinations([ 7, 10, 2, 5, 3, 1 ], 10) => [[7, 2, 1], [7, 3], [10], [2, 5, 3]] | |
* @returns {Array} | |
*/ | |
function findCombinations (ITEMS, target) | |
{ | |
var results = [], | |
i = 0, | |
l = ITEMS.length, | |
item; | |
for( ; i<l; i++ ) | |
{ // Проходим массив значений | |
item = ITEMS[i]; // Текущее значение | |
if( item > target ) continue; // Выходит за цель, отбросили, выходим | |
if( item == target ) { results.push([item]); continue; } // Оно, цепляем, выходим | |
var subResults = findCombinations(ITEMS.slice(i+1), target - item); // Ищем возможные варианты, исключая текущее значение | |
if( ! subResults.length ) continue;// Возможностей нет, отбросили, выходим | |
// console.log("subResults for", item, "is", subResults); // Все возможные варианты для текущего значения | |
for( var j=0, k=subResults.length; j<k; j++ ) | |
results.push([item].concat(subResults[j])); // Склеиваем результат | |
}; | |
return results; | |
}; | |
console.log( findCombinations([ 7, 10, 2, 5, 3, 1 ], 10) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment