Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs')
- // const input = fs.readFileSync('test.txt').toString().trim()
- const input = fs.readFileSync('input.txt').toString().trim()
- const range = (a) => [...Array(a).keys()]
- const abs = Math.abs
- const follow = (head, tail) => abs(head[0] - tail[0]) >= 2 || abs(head[1] - tail[1]) >= 2 ? head : null
- const move = (rope, [hx, hy]) => {
- const head = rope.head.at(-1)
- const tail = rope.tail.at(-1)
- const newHead = [head[0] + hx, head[1] + hy]
- return {
- head: [...rope.head, newHead],
- tail: follow(newHead, tail) ? [...rope.tail, [...head]] : rope.tail,
- }
- }
- const moves = {
- U: (current, count) => range(count).reduce((acc) => move(acc, [1, 0]), current),
- D: (current, count) => range(count).reduce((acc) => move(acc, [-1, 0]), current),
- L: (current, count) => range(count).reduce((acc) => move(acc, [0, -1]), current),
- R: (current, count) => range(count).reduce((acc) => move(acc, [0, 1]), current),
- }
- const pairs = input.split('\n').map((pair) => pair.split(' '))
- .reduce((acc, [direction, count]) => moves[direction](acc, +count), {
- head: [[0, 0]],
- tail: [[0, 0]],
- })
- console.log(new Set(pairs.tail.map((pairs) => pairs.join('_'))).size)
- const getModifiers = ([hx, hy], [tx, ty]) => {
- const x = abs(hx - tx) === 2 ? (hx - tx) / 2 :
- abs(hy - ty) === 2 ?
- (abs(hx - tx) === 1 ? hx - tx : 0)
- : 0
- const y = abs(hy - ty) === 2 ? (hy - ty) / 2 :
- abs(hx - tx) === 2 ?
- (abs(hy - ty) === 1 ? hy - ty : 0)
- : 0
- return [x, y]
- }
- const move2 = (rope, [hx, hy]) => {
- const head = [rope.knots[0][0] + hx, rope.knots[0][1] + hy]
- const knots = rope.knots.reduce((acc, knot, i) => {
- if (i === 0) {
- acc[i] = head
- return acc
- }
- const prev = acc[i - 1]
- const [dx, dy] = getModifiers(prev, acc[i])
- acc[i] = follow(prev, acc[i]) ? [acc[i][0] + dx, acc[i][1] + dy] : acc[i]
- return acc
- }, rope.knots.map(a => a.slice()))
- return {
- knots: knots,
- tail: [...rope.tail, knots.at(-1)],
- }
- }
- const moves2 = {
- U: (current, count) => range(count).reduce((acc) => move2(acc, [1, 0]), current),
- D: (current, count) => range(count).reduce((acc) => move2(acc, [-1, 0]), current),
- L: (current, count) => range(count).reduce((acc) => move2(acc, [0, -1]), current),
- R: (current, count) => range(count).reduce((acc) => move2(acc, [0, 1]), current),
- }
- const pairs2 = input.split('\n').map((pair) => pair.split(' '))
- .reduce((acc, [direction, count]) => moves2[direction](acc, +count), {
- knots: range(10).map(() => [0, 0]),
- tail: [],
- })
- console.log(new Set(pairs2.tail.map((s) => s.join('_'))).size)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement