Skip to content

Instantly share code, notes, and snippets.

@isarojdahal
Last active September 11, 2023 12:39
Show Gist options
  • Save isarojdahal/9ae124dafe74b0c601495e71a97a25cd to your computer and use it in GitHub Desktop.
Save isarojdahal/9ae124dafe74b0c601495e71a97a25cd to your computer and use it in GitHub Desktop.
/* Program to find probability for rolling of two dies for getting sums of die faces which are either less than or greater than or equal to given number */
const validateData = (input) => {
const result = input.match(/^[<|>|=][1-6]$/);
return result != null ? true : false;
};
const checkProbability = (sign, number) => {
let resultList = [];
let noOfExhaustiveEvent = 0; // this means our favorable event.
for (let i = 1; i <= 6; i++) {
for (let j = 1; j <= 6; j++) {
if (eval(`${i + j} ${sign} ${number}`)) {
resultList.push({ data: `(${i}, ${j})` });
noOfExhaustiveEvent++;
}
}
}
return { ...resultList, noOfExhaustiveEvent };
};
const evaluateProbability = (input) => {
const isValid = validateData(input);
if (isValid) {
const result = checkProbability(input.split("")[0], input.split("")[1]);
console.log(
result,
"Probability is : " +
parseFloat(result.noOfExhaustiveEvent / 36).toFixed(2)
);
} else
console.log(
"invalid input format ; try using >5 where signs are > , < or = and numbers are from 1 to 6"
);
};
//Example:
evaluateProbability(">3"); //getting more than 3
evaluateProbability("=5"); // sum equal to five
evaluateProbability(">7"); // sum greater than 7
// (1,1), (1,2), (1,3), (1,4), (1,5), (1,6)
// (2,1), (2,2), (2,3), (2,4), (2,5), (2,6)
// (3,1), (3,2), (3,3), (3,4), (3,5), (3,6)
// (4,1), (4,2), (4,3), (4,4), (4,5), (4,6)
// (5,1), (5,2), (5,3), (5,4), (5,5), (5,6)
// (6,1), (6,2), (6,3), (6,4), (6,5), (6,6)
//author : Saroj Dahal
//code : 2021 Oct 26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment