Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble simplifying conditional

I'm having trouble simplifying a conditional statement. It looks like this:
There is an array of arrays like this, dice = [ [a, b], [c, d] ].
a, b, c, and d representing random numbers on a dice 1 > 6.
Every array in the array represents a roll of two dice where the last roll is [c, d] = [2, 5] for example,
and the second-last roll is [a, b] = [3, 6] for example.
Now if you roll 2 x 1 in a row or 2 x 6 in a row something happens. so, a + c || a + d and b + c || b + d may not be 2 or 12.
The conditional below works but I think if you open the door to hell it looks prettier.
dice = last roll = [c, d]
prev = second last roll = [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
}
like image 255
Noud Avatar asked Oct 15 '25 14:10

Noud


2 Answers

I would do something like this:

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
}

In ES6 it is a little bit shorter:

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
}

What this actually does is calculate all combinations (additions) and then check whether one is 2 and one is 12.

like image 50
Stefan Jelner Avatar answered Oct 17 '25 04:10

Stefan Jelner


The condition can only happens when both dice and prev contain 1 or 6. So, we can just check that.

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")
}
like image 35
holydragon Avatar answered Oct 17 '25 04:10

holydragon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!