|
| 1 | +const { StdOut, StdRandom } = require('../../libs') |
| 2 | +const { Counter } = require('../../adts') |
| 3 | + |
| 4 | +/** |
| 5 | + * Flips |
| 6 | + * @classdesc Counter Client |
| 7 | + * @see p. 70, 71, 85, 89 |
| 8 | + */ |
| 9 | +class Flips { |
| 10 | + /** |
| 11 | + * Returns the counter with the max tally. |
| 12 | + * @param {Counter} counterX Counter X |
| 13 | + * @param {Counter} counterY Counter Y |
| 14 | + */ |
| 15 | + static max (counterX, counterY) { |
| 16 | + if (counterX.tally() > counterY.tally()) { |
| 17 | + return counterX |
| 18 | + } else { |
| 19 | + return counterY |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Simulates the flips of a coin and computes the delta. |
| 25 | + * @param {[]} args [trials] |
| 26 | + * @example |
| 27 | + * ```sh |
| 28 | + * $ node flips.client.js 1000 |
| 29 | + * 490 heads |
| 30 | + * 510 tails |
| 31 | + * delta: 20 |
| 32 | + * 510 tails wins |
| 33 | + * ``` |
| 34 | + */ |
| 35 | + static main (args) { |
| 36 | + const trials = parseInt(args[0], 10) |
| 37 | + const heads = new Counter('heads') |
| 38 | + const tails = new Counter('tails') |
| 39 | + |
| 40 | + for (let i = 0; i < trials; i++) { |
| 41 | + if (StdRandom.bernoulli(0.5)) { |
| 42 | + heads.increment() |
| 43 | + } else { |
| 44 | + tails.increment() |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + StdOut.println(heads.toString()) |
| 49 | + StdOut.println(tails.toString()) |
| 50 | + |
| 51 | + const delta = heads.tally() - tails.tally() |
| 52 | + |
| 53 | + StdOut.println(`delta: ${Math.abs(delta)}`) |
| 54 | + |
| 55 | + if (heads.tally() === tails.tally()) { |
| 56 | + StdOut.println(`It's a Tie!`) |
| 57 | + } else { |
| 58 | + StdOut.println(`${Flips.max(heads, tails)} wins`) |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +// Execution |
| 64 | +// ============================== |
| 65 | +Flips.main(process.argv.slice(2)) |
0 commit comments