js lang solution №3
This commit is contained in:
parent
6034154ee6
commit
43bdd6f1b4
1 changed files with 65 additions and 0 deletions
65
js/solution3.js
Normal file
65
js/solution3.js
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
function tenToBin(x) {
|
||||
const l = [];
|
||||
while (x !== 0) {
|
||||
l.push(x % 2);
|
||||
x = Math.trunc(x / 2);
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
function calculateSum(numbers, mask) {
|
||||
let x = 0;
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
if (mask[i] == 1) {
|
||||
x = x + numbers[i];
|
||||
}
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
function findSum(target, numbers) {
|
||||
const n = numbers.length;
|
||||
const totalCombinations = (1 << n) - 1;
|
||||
|
||||
for (let mask = 0; mask < totalCombinations; mask++) {
|
||||
let currentSum = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
// Проверяем i-й бит числа mask
|
||||
currentSum += (mask >> (i + 0) & 1) * numbers[i];
|
||||
}
|
||||
if (currentSum == target) {
|
||||
return tenToBin(mask);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
// 1. Валидация
|
||||
if (args.length < 5) {
|
||||
console.log("ER: input parameters");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (args.length > 30) {
|
||||
console.log("ER: input parameters");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 2. Формирование данных
|
||||
const target = parseInt(args[0], 10);
|
||||
const numbers = new Int32Array(args.slice(1).map(Number));
|
||||
|
||||
// 3. Запуск поиска
|
||||
const result = findSum(target, numbers);
|
||||
|
||||
if (result.length) {
|
||||
console.log("OK: ", result.join(''));
|
||||
} else {
|
||||
console.log("NO: not found.")
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Loading…
Add table
Add a link
Reference in a new issue