CTCIの真ん中、8.14:記号0(偽)、1(真)、&(AND) | (OR)、および^(XOR)、および所望のブール結果値の結果を評価するように、式をかっこする方法の数を数える関数を実装します。ブール式の文字列を括弧で括って目的の結果に評価する方法の数を数える方法
私は、可能なすべてのコンボを計算し、希望の結果と一致する場合はそれを配列に追加し(コンボ)、その結果の長さを返すブルートフォースアプローチを試みています。それはほとんどの表現ではうまくいくようですが、2番目の例ではありません。私は何が失われているように見えるのですか?
function countEval(s, goalBool, combos = []) {
// on first call make s into array since theyre easier to work with
if (!(s instanceof Array)) {
// and turn 1s and 0s into their bool equivalent
s = s.split('').map((item) => {
if (item === '1') {
return true;
} else if (item === '0'){
return false;
} else {
return item;
}
});
}
if (s.length === 1 && s[0] === goalBool) {
combos.push(s[0]); // can be anything really
} else {
for (let i = 0; i < s.length - 2; i = i + 2) {
// splice out the next 3 items
const args = s.splice(i, 3);
// pass them to see what they evaluate too
const result = evalHelper(args[0], args[1], args[2]);
// splice that result back in s array
s.splice(i, 0, result);
// pass that array to recurse
countEval(s, goalBool, combos);
// remove said item that was just put in
s.splice(i, 1);
// and reset array for next iteration
s.splice(i, 0, ...args);
}
}
return combos.length;
}
function evalHelper(a, op, b) {
if (op === '|') {
return a || b;
} else if (op === '&') {
return a && b;
} else if (op === '^') {
return a !== b;
}
}
それは最初のもののために働く与えられた2例では
が、2番目ない...
console.log(countEval('1^0|0|1', false)); // 2, correct
console.log(countEval('0&0&0&1^1|0', true)); // 30, should be 10!?!?!
わかりました...が、コードによって識別される30個の方法は何ですか?それを印刷することは大いに役立たないでしょうか? – Prune
@Pruneああ、ありがとう。私はやったし、彼らはまだ真実と評価されているようだ...私はその質問を理解できないと思う。しかし、まだ私のalgoが与えられた解とどのように違うのか分からないようです:/ – Afs35mm
あなたのアルゴリズムは式をかっこにする30の方法を特定しましたが、現実にはわずか10しかないと言われています。あなたのプログラムは、見つけた30の方法のそれぞれを印刷して、重複または間違った答えをどこで生成したのかを見てください。 – Prune