summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--day22/data.js57
-rw-r--r--day22/day22-1.js21
-rw-r--r--day22/day22-2.js40
3 files changed, 118 insertions, 0 deletions
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)
+