From 59e650785cf4b4bf9bdec0d679e6c05b41fc29fb Mon Sep 17 00:00:00 2001 From: Mark Jeeninga <mark.jeeninga@control.lth.se> Date: Sat, 14 Dec 2024 13:10:17 +0000 Subject: [PATCH] Day 6 Mark --- day 6/day_6_mark.js | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 day 6/day_6_mark.js diff --git a/day 6/day_6_mark.js b/day 6/day_6_mark.js new file mode 100644 index 0000000..b4b0589 --- /dev/null +++ b/day 6/day_6_mark.js @@ -0,0 +1,64 @@ +lines = input.split("\n").map(x=>x.split("")) +n = lines.length +m = lines[0].length +range = x => [...Array(x).keys()] +getEntry = x => lines[x[0]] ? lines[x[0]][x[1]] : undefined +setEntry = (x,y) => x[0] >= 0 && x[0] < n && x[1] >= 0 && x[1] < m ? lines[x[0]][x[1]] = y : undefined +done = true +direction = 0 +directions = [[-1,0],[0,1],[1,0],[0,-1]]; +guardStart = undefined +range(n).some(i => range(m).some(j => getEntry([i,j]) == "^" ? guardStart = [i,j] : false)) +guard = guardStart; +print = () => lines.map(x => x.join("")).join("\n") +while(guard){ + nextGuard = [guard[0]+directions[direction][0], guard[1]+directions[direction][1]] + while(getEntry(nextGuard) == "#"){ + direction = (direction + 1) % 4 + nextGuard = [guard[0]+directions[direction][0], guard[1]+directions[direction][1]] + } + setEntry(guard,"X") + guard = setEntry(nextGuard, "^") ? nextGuard : undefined +} + +output1 = range(n).reduce((x,i) => x+range(m).reduce((y,j) => y+(getEntry([i,j]) == "X" ? 1 : 0),0),0) + +isLoop = x => { + if(x.toString() == guardStart.toString()) + return false; + + lines = input.split("\n").map(x=>x.split("")) + setEntry(x, "#") + guard = guardStart; + getEntry = x => lines[x[0]] ? lines[x[0]][x[1]] : undefined + setEntry = (x,y) => x[0] >= 0 && x[0] < n && x[1] >= 0 && x[1] < m ? lines[x[0]][x[1]] = y : undefined + step = 0 + direction = 0 + while(guard){ + entry = typeof(getEntry(guard)) != "number" ? 0 : getEntry(guard) + if(entry & 2**direction){ + console.log(-1) + return true + } + setEntry(guard, entry | (2**direction)) + nextGuard = [guard[0]+directions[direction][0], guard[1]+directions[direction][1]] + counter = 0 + while(getEntry(nextGuard) == "#" && counter < 4){ + direction = (direction + 1) % 4 + nextGuard = [guard[0]+directions[direction][0], guard[1]+directions[direction][1]] + counter += 1 + } + if(counter == 4){ + console.log(-2) + return false; + } + if(step > m*n){ + console.log(-3) + return false; + } + guard = getEntry(nextGuard) ? nextGuard : undefined + step += 1 + } + return false; +} +output2 = range(n).reduce((x,i) => x+range(m).reduce((y,j) => y+isLoop([i,j]),0),0) -- GitLab