|
| 1 | +describe("Day 15 - Rambunctious Recitation", () => { |
| 2 | + describe("Part I", () => { |
| 3 | + test("Example", () => { |
| 4 | + expect(playMemory("0,3,6", 2020)).toEqual(436); |
| 5 | + expect(playMemory("3,1,2", 2020)).toEqual(1836); |
| 6 | + }); |
| 7 | + |
| 8 | + test("Input", () => { |
| 9 | + expect(playMemory("0,20,7,16,1,18,15", 2020)).toEqual(1025); |
| 10 | + }); |
| 11 | + }); |
| 12 | + |
| 13 | + describe("Part II", () => { |
| 14 | + test("Example", () => { |
| 15 | + expect(playMemory("0,3,6", 30_000_000)).toEqual(175594); |
| 16 | + expect(playMemory("3,1,2", 30_000_000)).toEqual(362); |
| 17 | + }); |
| 18 | + |
| 19 | + test("Input", () => { |
| 20 | + expect(playMemory("0,20,7,16,1,18,15", 30_000_000)).toEqual(129262); |
| 21 | + }); |
| 22 | + }); |
| 23 | +}); |
| 24 | + |
| 25 | +function playMemory(listStr: string, turnToReturn: number) { |
| 26 | + const initialList = listStr.split(",").map((n) => Number(n)); |
| 27 | + let mostRecentNum = NaN; |
| 28 | + let turnNo = initialList.length; |
| 29 | + |
| 30 | + const mostRecentPlayedAt = new Map<number, number>(); |
| 31 | + const prevPlayedAt = new Map<number, number>(); |
| 32 | + |
| 33 | + initialList.forEach((num, i) => { |
| 34 | + mostRecentPlayedAt.set(num, i + 1); // turn is a 1-based index |
| 35 | + mostRecentNum = num; |
| 36 | + }); |
| 37 | + |
| 38 | + while (turnNo < turnToReturn) { |
| 39 | + turnNo++; |
| 40 | + |
| 41 | + const mostRecent = mostRecentPlayedAt.get(mostRecentNum); |
| 42 | + const prev = prevPlayedAt.get(mostRecentNum); |
| 43 | + |
| 44 | + if (mostRecent !== undefined && prev !== undefined) { |
| 45 | + const newNum = mostRecent - prev; |
| 46 | + addNum(newNum); |
| 47 | + mostRecentNum = newNum; |
| 48 | + } else { |
| 49 | + addNum(0); |
| 50 | + mostRecentNum = 0; |
| 51 | + } |
| 52 | + |
| 53 | + if (turnNo === turnToReturn) { |
| 54 | + return mostRecentNum; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + function addNum(num: number, atTurn = turnNo) { |
| 59 | + const mostRecent = mostRecentPlayedAt.get(num); |
| 60 | + if (mostRecent !== undefined) { |
| 61 | + prevPlayedAt.set(num, mostRecent); |
| 62 | + mostRecentPlayedAt.set(num, atTurn); |
| 63 | + } else { |
| 64 | + mostRecentPlayedAt.set(num, atTurn); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return mostRecentNum; |
| 69 | +} |
0 commit comments