-
Notifications
You must be signed in to change notification settings - Fork 0
/
cards.js
65 lines (52 loc) · 1.47 KB
/
cards.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Output of program:
/*
$ node cards.js
isRed
- Average probability of being right: 3.84615384615385%
isFace
- Average probability of being right: 3.846153846153845%
isAceOfSpades
- Average probability of being right: 3.8461538461538396%
*/
// BUILD DECK
const faces = [..."A23456789TJQK"]; // T is Ten
const suits = [..."SCDH"];
const deck = [];
faces.forEach(face=>suits.forEach(suit=>deck.push(face + suit)))
// Define the queries
const isRed = (card) => 'DH'.indexOf(card[1]) !== -1;
const isFace = (card) => 'JQK'.indexOf(card[0]) !== -1;
const isAceOfSpades = (card) => card === 'AS';
const not = (query) => {
return (card) => !query(card)
}
// For each query
[
isRed,
isFace,
isAceOfSpades
].forEach(query => {
const inGroup = deck.filter(query);
const outGroup = deck.filter(not(query))
let probabilitySum = 0;
// Measure the probability of guessing the right card,
// given the answer to the query.
deck.forEach(randomSelection => {
const guesses = query(randomSelection) ? inGroup : outGroup;
let right = 0;
let wrong = 0;
let tries = 0;
guesses.forEach(guess=>{
if (guess === randomSelection) {
right++;
} else {
wrong++;
}
tries++;
});
probabilitySum += right / tries;
});
// Display the average probability of choosing correctly.
console.log(query.name);
console.log(` - Average probability of being right: \t${probabilitySum / deck.length * 100}%`);
});