История изменений
Исправление vbr, (текущая версия) :
У меня так получилось.
const expectedValue = 200;
const digits = ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0'];
const operations = ['', '+', '-'];
const permutation = new Uint8Array(digits.length - 1).fill(0);
do {
const expressionChars = [];
for (let i = 0; i < digits.length - 1; i++) {
expressionChars.push(digits[i]);
expressionChars.push(operations[permutation[i]]);
}
expressionChars.push(digits[digits.length - 1]);
const expressionString = expressionChars.join('');
const expressionValue = eval(expressionString);
if (expressionValue === expectedValue) console.log(expressionString);
} while (nextPermutation(permutation, operations.length));
function nextPermutation(permutation, cardinality) {
let i = permutation.length - 1;
while (i >= 0 && permutation[i] === cardinality - 1) {
permutation[i] = 0;
i--;
}
if (i < 0) return false;
permutation[i]++;
return true;
}
Исходная версия vbr, :
У меня так получилось.
const expectedValue = 200;
const digits = ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0'];
const operations = ['', '+', '-'];
const permutation = new Uint8Array(digits.length - 1).fill(0);
do {
const expressionChars = [];
for (let i = 0; i < digits.length - 1; i++) {
expressionChars.push(digits[i]);
expressionChars.push(operations[permutation[i]]);
}
expressionChars.push(digits[digits.length - 1]);
const expressionString = expressionChars.join('');
const expressionValue = eval(expressionString);
if (expressionValue === expectedValue) {
console.log(expressionString);
}
} while (nextPermutation(permutation, operations.length));
function nextPermutation(permutation, cardinality) {
let i = permutation.length - 1;
while (i >= 0 && permutation[i] === cardinality - 1) {
permutation[i] = 0;
i--;
}
if (i < 0) return false;
permutation[i]++;
return true;
}