js lang solution №1
This commit is contained in:
parent
d3ac3e74fb
commit
04eede7e76
1 changed files with 62 additions and 0 deletions
62
js/solution1.js
Normal file
62
js/solution1.js
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
function tenToBin(x) {
|
||||||
|
const l = [];
|
||||||
|
let i = x;
|
||||||
|
while (i !== 0) {
|
||||||
|
l.push(i % 2);
|
||||||
|
i = Math.trunc(i / 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 totalCombinations = Math.pow(2, numbers.length) - 1;
|
||||||
|
for (let index = 0; index < totalCombinations; index++) {
|
||||||
|
const mask = tenToBin(index);
|
||||||
|
const currentSum = calculateSum(numbers, mask);
|
||||||
|
if (currentSum == target) {
|
||||||
|
console.log(mask);
|
||||||
|
return 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 = 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