summaryrefslogtreecommitdiffstats
path: root/day22/day22-2.js
diff options
context:
space:
mode:
authorGravatar Piotr Russ <mail@pruss.it> 2020-12-25 01:02:32 +0100
committerGravatar Piotr Russ <piotr.russ@betvictor.com> 2020-12-25 08:10:10 +0100
commitf3273983a827b01a12f1ddf6215f8d69938821eb (patch)
treedb95c97e3686967e70827fdcea797aa53dc0b115 /day22/day22-2.js
parentda3b7eacf125f1569fa5c5b50b60941a65d5067f (diff)
downloadadvent_of_code_2020-f3273983a827b01a12f1ddf6215f8d69938821eb.tar.gz
advent_of_code_2020-f3273983a827b01a12f1ddf6215f8d69938821eb.tar.bz2
advent_of_code_2020-f3273983a827b01a12f1ddf6215f8d69938821eb.zip
day22
Diffstat (limited to 'day22/day22-2.js')
-rw-r--r--day22/day22-2.js40
1 files changed, 40 insertions, 0 deletions
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)
+