js lang solution №2
This commit is contained in:
parent
2feb7c18e9
commit
5983863625
1 changed files with 70 additions and 0 deletions
70
js/solution2.js
Normal file
70
js/solution2.js
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
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
|
||||||
|
if ((mask >> i) & 1) {
|
||||||
|
currentSum += numbers[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentSum == target) {
|
||||||
|
return tenToBin(mask);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Точка входа (Аналог main)
|
||||||
|
*/
|
||||||
|
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 = args.slice(1).map(Number);
|
||||||
|
|
||||||
|
// 3. Запуск поиска
|
||||||
|
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