我在簡化條件陳述句時遇到了麻煩。它看起來像這樣:
有一個這樣的陣列陣列,dice = [ [a, b], [c, d] ]。
a、b、c 和 d 表示骰子 1 > 6 上的亂數。
陣列中的每個陣列都表示兩個骰子的擲骰,例如,最后擲骰是 [c, d] = [2, 5],
而例如倒數第二卷是 [a, b] = [3, 6]。
現在,如果您連續滾動 2 x 1 或連續滾動 2 x 6,就會發生一些事情。所以,a c || a d 和 b c || b d 可能不是 2 或 12。
下面的條件有效,但我認為如果你打開地獄之門,它看起來更漂亮。
骰子 = 最后一卷 = [c, d]
prev = 倒數第二個 = [a, b]
if (dice[0] prev[0] === 2 || dice[1] prev[1] === 2 || dice[1] prev[0] === 2 || dice[0]
prev[1] === 2 &&
dice[0] prev[0] === 12 || dice[1] prev[1] === 12 || dice[1] prev[0] === 12 || dice[0]
prev[1] === 12){
//something happens here
}
uj5u.com熱心網友回復:
我會做這樣的事情:
var combinations = dice.reduce(function(acc, curr) {
return acc.concat(prev.map(function(curr2) {
return curr curr2;
}));
}, []);
if (combinations.indexOf(2) !== -1 && combinations.indexOf(12) !== -1) {
//something happens here
}
在 ES6 中它有點短:
const combinations = dice.reduce((acc, curr) => acc.concat(prev.map(curr2 => curr curr2)), []);
if (combinations.indexOf(2) !== -1 && combinations.indexOf(12) !== -1) {
//something happens here
}
這實際上是計算所有組合(加法),然后檢查一個是 2 還是一個是 12。
uj5u.com熱心網友回復:
只有當兩者都dice包含prev1 或 6 時才會發生這種情況。所以,我們可以檢查一下。
let throws = [[5,3],[1,6]];
let prev = throws[0];
let dice = throws[1];
if ((prev.includes(1) && dice.includes(1)) || (prev.includes(6) && dice.includes(6))){
console.log("2 or 12 occurs")
}
else {
console.log("2 and 12 do not occur")
}
uj5u.com熱心網友回復:
像下面這樣的東西呢?:
const one_and_six_found = (roll) => roll.includes(1) && roll.includes(6);
const two_rolls_have_one_and_six = (roll1, roll2) =>
one_and_six_found(roll1) && one_and_six_found(roll2);
console.log(two_rolls_have_one_and_six( [1, 6], [1, 6] ));
console.log(two_rolls_have_one_and_six( [6, 1], [1, 6] ));
console.log(two_rolls_have_one_and_six( [5, 1], [1, 6] ));
uj5u.com熱心網友回復:
我提出了一個更適合您需求的更簡單的解決方案
const throws1 = [[1, 2], [3, 4]]
const throws2 = [[1, 2], [3, 1]]
const throws3 = [[1, 6], [6, 1]]
const checkCondition = (prev, dice) => [1, 6].every(res => prev.includes(res) && dice.includes(res))
console.log(checkCondition(...throws1))
console.log(checkCondition(...throws2))
console.log(checkCondition(...throws3))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471207.html
標籤:javascript 算法 if 语句
