Skip to content

Instantly share code, notes, and snippets.

@Bitaru
Created January 23, 2014 07:27
Show Gist options
  • Select an option

  • Save Bitaru/8574397 to your computer and use it in GitHub Desktop.

Select an option

Save Bitaru/8574397 to your computer and use it in GitHub Desktop.
Напишите функцию, которая из произвольного входящего массива выберет все комбинации чисел, сумма которых будет равняться 10.
(function() {
arrayMath = function(input, subject) {
var array, bin, c, count, counter, d,
fx, i, index, item, like, match,
output, reverse, sample, v, zip, _i, _len;
array = [];
for (_i = 0, _len = input.length; _i < _len; _i++) { // # Очищаем входящий массив
item = input[_i];
if (item < subject && isFinite(item)) {
array.push(item); // # Для проверки уникальности при сборе финального хэша
}
}
array.sort();
output = {};
count = array.length;
counter = 0;
fx = Math.pow(2, count) - 1; // # 2^n–1
for (i = 1; i <= fx; i++) {
bin = i.toString(2);
zip = Array(count + 1 - bin.length).join("0") + bin;
reverse = zip.split("").reverse();
d = 0;
like = 0;
index = '';
sample = [];
for (c = 0; c <= count; c++) {
_i = reverse[c];
if (_i === '1') {
match = array[d];
sample.push(match);
like = like + match;
index += like;
}
d++;
}
if (like === subject && !output[index]) { // # Проверяем уникальность
output[index] = sample;
counter++;
}
}
for (i in output) {
console.log(output[i]);
}
return "Комбинаций: " + counter;
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment