From f3273983a827b01a12f1ddf6215f8d69938821eb Mon Sep 17 00:00:00 2001 From: Piotr Russ Date: Fri, 25 Dec 2020 01:02:32 +0100 Subject: day22 --- day22/data.js | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ day22/day22-1.js | 21 +++++++++++++++++++++ day22/day22-2.js | 40 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 day22/data.js create mode 100644 day22/day22-1.js create mode 100644 day22/day22-2.js (limited to 'day22') diff --git a/day22/data.js b/day22/data.js new file mode 100644 index 0000000..e85ae4e --- /dev/null +++ b/day22/data.js @@ -0,0 +1,57 @@ +const data = ` +Player 1: +47 +19 +22 +31 +24 +6 +10 +5 +1 +48 +46 +27 +8 +45 +16 +28 +33 +41 +42 +36 +50 +39 +30 +11 +17 + +Player 2: +4 +18 +21 +37 +34 +15 +35 +38 +20 +23 +9 +25 +32 +13 +26 +2 +12 +44 +14 +49 +3 +40 +7 +43 +29 +` + +module.exports = data diff --git a/day22/day22-1.js b/day22/day22-1.js new file mode 100644 index 0000000..f2528f5 --- /dev/null +++ b/day22/day22-1.js @@ -0,0 +1,21 @@ +const data = require('./data') +const [player1, player2] = data.split('\n\n').filter(Boolean) + .map(p => p.split(/\n/g).filter(Boolean).slice(1)) + +const round = () => { + const c1 = player1.shift() + const c2 = player2.shift() + if (parseInt(c1) > parseInt(c2)) { + player1.push(c1, c2) + } else { + player2.push(c2, c1) + } +} + +while (player1.length>0 && player2.length>0) { round() } + +const cards = player1.length > 0 ? player1 : player2 +const score = cards.reverse().map((c, i) => parseInt(c) * (i+1)).reduce((a,b) => a + b, 0) + +console.log('Answer: ', score) + diff --git a/day22/day22-2.js b/day22/day22-2.js new file mode 100644 index 0000000..e79d8e7 --- /dev/null +++ b/day22/day22-2.js @@ -0,0 +1,40 @@ +const data = require('./data') +const [player1, player2] = data + .split('\n\n').filter(Boolean) + .map(p => p.split(/\n/g).filter(Boolean).slice(1).map(n => parseInt(n))) + +const game = (players, rec = false) => { + const prev = {} + const p1 = players[0] + const p2 = players[1] + + while (players.every((player) => player.length > 0)) { + const k = players.map(p => p.join(',')).join('|') + if (prev[k]) { return [[1], []] } + prev[k] = true + + const c1 = p1.shift() + const c2 = p2.shift() + + if (rec && p1.length >= c1 && p2.length >= c2) { + const [r1, r2] = game([[...p1.slice(0, c1)], [...p2.slice(0, c2)]], true) + if (r1.length > r2.length) { + p1.push(c1, c2) + } else { + p2.push(c2, c1) + } + } else if (c1 > c2) { + p1.push(c1, c2) + } else { + p2.push(c2, c1) + } + } + + return players +} + +const score = game([player1, player2], true).flat().reverse() + .map((c, i) => parseInt(c) * (i+1)).reduce((a,b) => a+b, 0) + +console.log('Answer: ', score) + -- cgit v1.2.3