|
| 1 | +/* === TYPES === */ |
| 2 | + |
| 3 | +/* === PREPARE INPUT === */ |
| 4 | + |
| 5 | +export const prepareInput = ([input]: TemplateStringsArray) => |
| 6 | + input |
| 7 | + .split("\n\n") |
| 8 | + .map((block) => block.split("\n")) |
| 9 | + .map<number[]>(([_player, ...deck]) => deck.map(Number)) as [ |
| 10 | + number[], |
| 11 | + number[] |
| 12 | + ]; |
| 13 | + |
| 14 | +/* === UTILS === */ |
| 15 | +const isEmpty = (arr: unknown[]): boolean => arr.length === 0; |
| 16 | + |
| 17 | +const getScore = (arr: number[]): number => |
| 18 | + [...arr] |
| 19 | + .reverse() |
| 20 | + .map((n, i) => n * (i + 1)) |
| 21 | + .reduce((a, b) => a + b, 0); |
| 22 | + |
| 23 | +/* === IMPLEMENTATION === */ |
| 24 | +const combat = ([deck1, deck2]: [number[], number[]]): [number[], number[]] => { |
| 25 | + if (isEmpty(deck1) || isEmpty(deck2)) return [deck1, deck2]; |
| 26 | + |
| 27 | + const [top1, ...rest1] = deck1; |
| 28 | + const [top2, ...rest2] = deck2; |
| 29 | + |
| 30 | + if (top1 > top2) { |
| 31 | + return combat([[...rest1, top1, top2], rest2]); |
| 32 | + } else { |
| 33 | + return combat([rest1, [...rest2, top2, top1]]); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +/* === TESTS === */ |
| 38 | + |
| 39 | +test("Day 22a - test", () => { |
| 40 | + const [deck1, deck2] = combat(testInput); |
| 41 | + |
| 42 | + expect(deck2).toEqual([3, 2, 10, 6, 8, 5, 9, 4, 7, 1]); |
| 43 | + |
| 44 | + expect(getScore(deck1) + getScore(deck2)).toBe(306); |
| 45 | +}); |
| 46 | + |
| 47 | +test("Day 22a - prod", () => { |
| 48 | + const [deck1, deck2] = combat(prodInput); |
| 49 | + |
| 50 | + expect(getScore(deck1) + getScore(deck2)).toBe(31629); |
| 51 | +}); |
| 52 | + |
| 53 | +test.skip("Day 22b - test", () => {}); |
| 54 | + |
| 55 | +test.skip("Day 22b - prod", () => {}); |
| 56 | + |
| 57 | +/* === INPUTS === */ |
| 58 | + |
| 59 | +const testInput = prepareInput`Player 1: |
| 60 | +9 |
| 61 | +2 |
| 62 | +6 |
| 63 | +3 |
| 64 | +1 |
| 65 | +
|
| 66 | +Player 2: |
| 67 | +5 |
| 68 | +8 |
| 69 | +4 |
| 70 | +7 |
| 71 | +10`; |
| 72 | + |
| 73 | +const prodInput = prepareInput`Player 1: |
| 74 | +28 |
| 75 | +50 |
| 76 | +9 |
| 77 | +11 |
| 78 | +4 |
| 79 | +45 |
| 80 | +19 |
| 81 | +26 |
| 82 | +42 |
| 83 | +43 |
| 84 | +31 |
| 85 | +46 |
| 86 | +21 |
| 87 | +40 |
| 88 | +33 |
| 89 | +20 |
| 90 | +7 |
| 91 | +6 |
| 92 | +17 |
| 93 | +44 |
| 94 | +5 |
| 95 | +39 |
| 96 | +35 |
| 97 | +27 |
| 98 | +10 |
| 99 | +
|
| 100 | +Player 2: |
| 101 | +18 |
| 102 | +16 |
| 103 | +29 |
| 104 | +41 |
| 105 | +14 |
| 106 | +12 |
| 107 | +30 |
| 108 | +37 |
| 109 | +36 |
| 110 | +24 |
| 111 | +48 |
| 112 | +38 |
| 113 | +47 |
| 114 | +34 |
| 115 | +15 |
| 116 | +8 |
| 117 | +49 |
| 118 | +23 |
| 119 | +1 |
| 120 | +3 |
| 121 | +32 |
| 122 | +25 |
| 123 | +22 |
| 124 | +13 |
| 125 | +2`; |
0 commit comments