Last active
December 28, 2021 21:41
-
-
Save emoryy/581029edb6e51dfbdd81658f00d5e35c to your computer and use it in GitHub Desktop.
Advent of Code 2021
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
const hexa = document.body.firstChild.textContent; | |
const input = hexa.match(/\w/g).map(num => Number.parseInt(num,16).toString(2).padStart(4,'0')).join('').split(''); | |
console.log("input", input.length, input.join('')); | |
let pos = 0; | |
let versionSum = 0; | |
function dec(bits) { | |
return Number.parseInt(bits, 2) | |
} | |
function take(n, toDec = true) { | |
const bits = input.slice(pos, pos + n).join(''); | |
console.log("reading", n, "bits", 'from', pos, bits); | |
if (!bits.length) { | |
throw "!!!NO MORE BITS!!!"; | |
} | |
pos += n; | |
return toDec ? dec(bits) : bits; | |
} | |
const packets = []; | |
let literal = {}; | |
const operators = []; | |
function currentOp(key, value) { | |
const curOp = operators[operators.length-1]; | |
if (!curOp) { | |
return null; | |
} | |
return value !== undefined ? (curOp[key] = value) : curOp[key]; | |
} | |
let root; | |
let currentOperator; | |
let currentPacket; | |
const funcs = { | |
START_PACKET: () => { | |
const newPacket = {}; | |
if (!root) { | |
root = newPacket; | |
console.log("ROOT", root); | |
} else { | |
currentOperator.zpackets.push(newPacket); | |
} | |
currentPacket = newPacket; | |
return "HEADER"; | |
}, | |
HEADER: () => { | |
const version = take(3); | |
versionSum+=version; | |
currentPacket.version = version; | |
console.log("version", version); | |
console.log("versionSum", versionSum); | |
const type = take(3); | |
console.log("type", type); | |
currentPacket.type = type; | |
if (type === 4) { | |
return "LITERAL"; | |
} | |
return "OPERATOR"; | |
}, | |
END_PACKET: () => { | |
const hasOperators = operators.length; | |
if (hasOperators) { | |
let popped; | |
do { | |
popped = null; | |
if (currentOp("lengtTypeId")) { | |
const subPCount = currentOp('subPacketCount'); | |
if (typeof subPCount === "number") { | |
currentOp('subPacketCount', subPCount - 1); | |
console.log("subPacketCount", currentOp("subPacketCount")); | |
if (currentOp('subPacketCount') === 0) { | |
popped = operators.pop(); | |
console.log("END OPERATOR (CNT)"); | |
} | |
} | |
} else { | |
const totalLength = currentOp('totalLength'); | |
if ((pos - currentOp('start')) >= totalLength) { | |
popped = operators.pop(); | |
console.log("END OPERATOR (LEN)"); | |
} | |
} | |
console.log("popped", popped); | |
} while (popped && operators.length); | |
} | |
if (hasOperators && !operators.length) { | |
console.log("-END REACHED-"); | |
return; | |
} | |
if (pos < input.length) { | |
return "START_PACKET"; | |
} else { | |
console.log("-END REACHED-"); | |
} | |
}, | |
LITERAL: () => { | |
literal.count = 0; | |
literal.notLast = 1; | |
literal.groups = ''; | |
return "LITERAL_GROUP"; | |
}, | |
LITERAL_GROUP: () => { | |
literal.notLast = take(1); | |
console.log("notLast", literal.notLast); | |
const group = take(4, false); | |
literal.groups += group; | |
if (!literal.notLast) { | |
const value = dec(literal.groups); | |
console.log("literal", value); | |
currentPacket.value = value; | |
return "END_PACKET"; | |
} | |
return "LITERAL_GROUP"; | |
}, | |
OPERATOR: () => { | |
operators.push({ | |
}); | |
currentPacket.zpackets = []; | |
currentOperator = currentPacket; | |
console.log("operator level", operators.length); | |
const lengthTypeId = take(1); | |
console.log("lengthTypeId", lengthTypeId); | |
currentPacket.lengthTypeId = lengthTypeId; | |
currentOp("lengthTypeId", lengthTypeId); | |
if (lengthTypeId) { | |
currentOp("subPacketCount", take(11)); | |
currentPacket.subPacketCount = currentOp("subPacketCount"); | |
console.log("subPacketCount", currentOp("subPacketCount")); | |
} else { | |
currentOp("totalLength", take(15)); | |
currentPacket.totalLength = currentOp("totalLength"); | |
if (currentPacket.totalLength > input.length - pos) { | |
throw `total length ${currentPacket.totalLength} remaining ${input.length - pos}`; | |
} | |
console.log("totalLength", currentOp("totalLength")); | |
currentOp("start", pos); | |
} | |
return "START_PACKET"; | |
} | |
}; | |
let state = "START_PACKET"; | |
while (state) { | |
console.log("### "+state+" ###"); | |
state = funcs[state](); | |
} | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
const hexa = document.body.firstChild.textContent; | |
const input = hexa.match(/\w/g).map(num => Number.parseInt(num,16).toString(2).padStart(4,'0')).join('').split(''); | |
console.log("input", input.length, input.join('')); | |
let pos = 0; | |
let versionSum = 0; | |
function dec(bits) { | |
return Number.parseInt(bits, 2) | |
} | |
function take(n, toDec = true) { | |
const bits = input.slice(pos, pos + n).join(''); | |
console.log("reading", n, "bits", 'from', pos, bits); | |
if (!bits.length) { | |
throw "!!!NO MORE BITS!!!"; | |
} | |
pos += n; | |
return toDec ? dec(bits) : bits; | |
} | |
let root; | |
const operators = []; | |
let currentOperator; | |
let currentPacket; | |
const funcs = { | |
START_PACKET: () => { | |
const newPacket = {}; | |
if (!root) { | |
root = newPacket; | |
console.log("ROOT", root); | |
} else { | |
currentOperator.zpackets.push(newPacket); | |
} | |
currentPacket = newPacket; | |
return "HEADER"; | |
}, | |
HEADER: () => { | |
const version = take(3); | |
versionSum+=version; | |
currentPacket.version = version; | |
const type = take(3); | |
console.log("type", type); | |
currentPacket.type = type; | |
if (type === 4) { | |
return "LITERAL"; | |
} | |
return "OPERATOR"; | |
}, | |
END_PACKET: () => { | |
const hasOperators = operators.length; | |
if (hasOperators) { | |
let popped; | |
do { | |
popped = null; | |
if (currentOperator.lengthTypeId) { | |
currentOperator.subPacketCount--; | |
if (currentOperator.subPacketCount === 0) { | |
popped = operators.pop(); | |
console.log("END OPERATOR (CNT)"); | |
} | |
} else { | |
if ((pos - currentOperator.start) >= currentOperator.totalLength) { | |
popped = operators.pop(); | |
console.log("END OPERATOR (LEN)"); | |
} | |
} | |
if (popped) { | |
currentOperator = operators[operators.length - 1]; | |
} | |
} while (popped && operators.length); | |
} | |
if (hasOperators && !operators.length) { | |
console.log("-END REACHED-"); | |
return; | |
} | |
if (pos < input.length) { | |
return "START_PACKET"; | |
} else { | |
console.log("-END REACHED-"); | |
} | |
}, | |
LITERAL: () => { | |
currentPacket.count = 0; | |
currentPacket.groups = ''; | |
return "LITERAL_GROUP"; | |
}, | |
LITERAL_GROUP: () => { | |
const notLast = take(1); | |
const group = take(4, false); | |
currentPacket.groups += group; | |
if (!notLast) { | |
const value = dec(currentPacket.groups); | |
console.log("literal", value); | |
currentPacket.value = value; | |
delete currentPacket.groups; | |
return "END_PACKET"; | |
} | |
return "LITERAL_GROUP"; | |
}, | |
OPERATOR: () => { | |
operators.push(currentPacket); | |
currentOperator = currentPacket; | |
currentOperator.zpackets = []; | |
const lengthTypeId = take(1); | |
currentPacket.lengthTypeId = lengthTypeId; | |
if (lengthTypeId) { | |
currentOperator.subPacketCount = take(11); | |
currentOperator.originalSubPacketCount = currentOperator.subPacketCount; | |
} else { | |
currentOperator.totalLength = take(15); | |
if (currentOperator.totalLength > input.length - pos) { | |
throw `total length ${currentOperator.totalLength} remaining ${input.length - pos}`; | |
} | |
currentOperator.start = pos; | |
} | |
return "START_PACKET"; | |
} | |
}; | |
let state = "START_PACKET"; | |
while (state) { | |
console.log("### "+state+" ###"); | |
state = funcs[state](); | |
} | |
const operatorFunctions = [ | |
(...operands) => operands.reduce((sum, cur) => sum + cur, 0), | |
(...operands) => operands.reduce((sum, cur) => sum * cur, 1), | |
(...operands) => Math.min(...operands), | |
(...operands) => Math.max(...operands), | |
undefined, | |
(op1, op2) => op1 > op2 ? 1 : 0, | |
(op1, op2) => op1 < op2 ? 1 : 0, | |
(op1, op2) => op1 === op2 ? 1 : 0, | |
]; | |
const result = (function process(packet) { | |
if (packet.type === 4) { | |
return packet.value; | |
} | |
return operatorFunctions[packet.type](...packet.zpackets.map(process)); | |
})(root); | |
console.log("result", result); | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.firstChild.innerText.match(/\d+/g).map(Number).reduce((acc, v, i, a) => i > 0 ? (v > a[i-1] ? acc + 1 : acc) : 0, 0); | |
document.firstChild.innerText.match(/\d+/g).map(Number).reduce((acc, v, i, a) => i > 2 ? (v > a[i-3] ? acc + 1 : acc) : 0, 0); | |
document.body.firstChild.textContent.match(/(\w+|\d+)/g).map((matched) => Number(matched) || matched[0]).reduce((acc, value, index, array) => (index % 2 === 0 ? (acc.command = value) : acc[acc.command] += value, index < array.length - 1 ? acc : (acc.f * (acc.d - acc.u))), {f: 0, d: 0, u: 0}) | |
document.body.firstChild.textContent.match(/(\w+|\d+)/g).map((matched) => Number(matched) || matched[0]).reduce((acc, value, index, array) => (index % 2 === 0 ? (acc.command = value) : (acc.command === "f" ? (acc[acc.command] += value, acc.d += acc.a * value) : acc.a += {u: -1, d: 1}[acc.command] * value), index < array.length - 1 ? acc : (acc.f * acc.d)), {f: 0, d: 0, a: 0}) | |
document.body.firstChild.textContent.match(/\d+/g).reduce((acc, row, i, array) => (row.split('').forEach((ch, i) => acc[i] = (acc[i] || 0) + Number(ch)), i < array.length - 1 ? acc : acc.map((count) => Math.round(count / array.length))), []).reduce((results, digit, i, digits) => (i === 0 ? results[0] = digits : '🙃', results[1][i] = 1 - digit, results), [[],[]]).map(digits => Number.parseInt(digits.join(''), 2)).reduce((γ, ε) => γ * ε) | |
(([firstRow, ...rest]) => [0, 1].map((x) => firstRow.split('').reduce((rows, _, i) => [rows, Number(rows.filter(row => Number(row[i])).length >= rows.length / 2)].reduce((rows, filterVal) => rows.length > 1 ? rows.filter(row => Number(row[i]) === (x ? filterVal : 1 - filterVal)) : rows),[firstRow, ...rest])).map(digits => Number.parseInt(digits.join(''), 2)).reduce((co2, o2) => co2 * o2))(document.body.firstChild.textContent.match(/\d+/g)); | |
(((process, check, draws, ...boards) => (((processedBoards) => draws.reduce((acc, draw, i) => ((!acc[0] ? (acc[1] = draws.slice(0, i + 1), acc[0] = processedBoards.find((procBoard) => check(procBoard, acc[1]))) : null), acc), []))(boards.map((board) => process(board)))))((board) => board.reduce((processedBoards, num, i, board) => (processedBoards[0][Math.floor(i / 5)].push(num), processedBoards[1][i % 5].push(num), processedBoards ), [0, 0].map(() => new Array(5).fill(1).map(() => ([])))), (procBoard, draws) => procBoard.find((board) => board.find((series) => series.filter((v) => draws.includes(v)).length === 5)), ...document.body.firstChild.textContent.split("\n\n").map(g => g.match(/\d+/g)))).reduce((winner, draws) => winner[0].flat().filter((num) => !draws.includes(num)).reduce((sum, v) => sum + Number(v), 0) * Number(draws.pop())) | |
(((process, check, draws, ...boards) => (((processedBoards) => draws.reduce((acc, draw, i) => ((acc[i] = { draw, draws: draws.slice(0, i + 1) }, acc[i].boards = processedBoards.filter((procBoard) => !procBoard.win && check(procBoard, acc[i].draws) && (procBoard.win = acc[i].draws.slice(), true))), acc), []))(boards.map((board) => process(board)))))((board) => board.reduce((processedBoards, num, i, board) => (processedBoards[0][Math.floor(i / 5)].push(num), processedBoards[1][i % 5].push(num), processedBoards), [0, 0].map(() => new Array(5).fill(1).map(() => ([])))), (procBoard, draws) => procBoard.find((board) => board.find((series) => series.filter((v) => draws.includes(v)).length === 5)), ...document.body.firstChild.textContent.split("\n\n").map(g => g.match(/\d+/g)) )).reverse().find((entry) => entry.boards.length).boards[0].reduce((winner1, winner2, i, winners) => [winner1.flat().reduce((sum, num) => sum + (!winners.win.includes(num) ? Number(num) : 0), 0), winners.win.pop()]).reduce((a, b) => a * b) | |
((input, proc) => Object.values(input.reduce((output, coords, i) => (proc(coords, output), output), {})).reduce((sum, x) => (x > 1 ? sum + 1: sum), 0))( document.body.firstChild.textContent.split("\n").filter((r) => r).map((row) => row.match(/\d+/g).map((numStr) => Number(numStr))).filter(([a,b,c,d]) => a === c || b === d).map(([x1, y1, x2, y2]) => (x1 > x2 || y1 > y2) ? [x2, y2, x1, y1] : [x1, y1, x2, y2]), function process([x1, y1, x2, y2], output) { const key = `${x1},${y1}`; output[key] = (output[key] || 0) + 1; if (x1 !== x2 || y1 !== y2) process([x1 === x2 ? x1 : x1 + 1, y1 === y2 ? y1 : y1 + 1, x2, y2], output); }) | |
((input, proc) => Object.values(input.reduce((output, coords, i) => (proc(coords, output), output), {})).reduce((sum, x) => (x > 1 ? sum + 1: sum), 0))(document.body.firstChild.textContent.split("\n").filter((r) => r).map((row) => row.match(/\d+/g).map((numStr) => Number(numStr))), function process([x1, y1, x2, y2], output) { const key = `${x1},${y1}`; output[key] = (output[key] || 0) + 1; if (x1 !== x2 || y1 !== y2) { process([ x1 < x2 ? x1 + 1 : (x1 > x2 ? x1 - 1 : x1), y1 < y2 ? y1 + 1 : (y1 > y2 ? y1 - 1 : y1), x2, y2], output); } }) | |
((input) => new Array(80).fill(1).reduce((acc) => (((zeroDay) => (acc[6] = (acc[6] || 0) + (zeroDay || 0), acc[8] = (zeroDay || 0)))(acc.shift()),acc), input))(document.body.firstChild.textContent.match(/\d+/g).map(Number).reduce((acc, cur) => (acc[cur] = (acc[cur] || 0) + 1, acc), [])).reduce((sum, num) => sum + (num || 0), 0) | |
((input) => new Array(256).fill(1).reduce((acc) => (((zeroDay) => (acc[6] = (acc[6] || 0) + (zeroDay || 0), acc[8] = (zeroDay || 0)))(acc.shift()),acc), input))(document.body.firstChild.textContent.match(/\d+/g).map(Number).reduce((acc, cur) => (acc[cur] = (acc[cur] || 0) + 1, acc), [])).reduce((sum, num) => sum + (num || 0), 0) | |
((input) => [Math.min(...input),Math.max(...input)].reduce((min,max) => (Math.min(...Array.from(Array(max-min), (_, i) => input.map((pos) => Math.abs(pos - (min + i))).reduce((sum, a) => sum + a, 0) )))))(document.body.firstChild.textContent.match(/\d+/g).map(Number)) | |
((input,fuelFunc) => [Math.min(...input),Math.max(...input)].reduce((min,max) => (Math.min(...Array.from(Array(max-min), (_, i) => input.map( (pos) => fuelFunc(Math.abs(pos - (min + i)))).reduce((sum, a) => sum + a, 0))))))(document.body.firstChild.textContent.match(/\d+/g).map(Number), (n) => (1+n)*n/2) | |
((map) => document.body.firstChild.textContent.match(/\|.+/g).map((o) => o.match(/\w+/g)).flat().reduce((count, str) => count + (map[str.length] || 0), 0))({2: 1, 3: 1, 4: 1, 7: 1}) | |
((segmentsOfNums, input) => (Array.prototype.remove = function(items) { const _items = Array.isArray(items) ? items : [items]; for(let i = 0; i < this.length; i++){ if (_items.includes(this[i])) { this.splice(i, 1); i--; } } return this; }, input.reduce((sum, [notes, output]) => { const pairings = ['a', 'b', 'c', 'd', 'e', 'f', 'g'].reduce( (map, letter, i, array) => (map[letter] = array.slice(), map), {} ); const one = notes.find((dig) => dig.length === 2); pairings.c = one.slice(); pairings.f = one.slice(); ['b', 'd', 'e', 'g'].forEach((seg) => pairings[seg].remove(one)); pairings.a = notes.find((dig) => dig.length === 3).slice().remove(one); const four = notes.find((dig) => dig.length === 4); const fourRem = four.filter((seg) => !one.includes(seg)); ['c', 'e', 'f', 'g'].forEach((seg) => pairings[seg].remove(fourRem)); pairings.b = fourRem.slice(); pairings.d = fourRem.slice(); ['e', 'g'].forEach((seg) => pairings[seg].remove(pairings.a)); const sixs = notes.filter((n) => n.length === 6); const sixsRemovedFour = sixs.map((digits) => digits.slice().remove(four).remove(pairings.a)); const common = sixsRemovedFour.filter(s => s.length === 1)[0][0]; pairings.e = [sixsRemovedFour.map((six) => six.remove(common)).flat()[0]]; pairings.g.remove(pairings.e); const sixsRemovedAGE = sixs.map( (digits) => digits.slice().remove(pairings.a).remove(pairings.g).remove(pairings.e) ); pairings.d = [pairings.d.find((digit) => sixsRemovedAGE.filter((x) => x.includes(digit)).length === 2)]; pairings.b = pairings.b.remove(pairings.d); pairings.c = [pairings.c.find((p) => sixs.filter((x) => x.includes(p)).length === 2)]; pairings.f = pairings.f.remove(pairings.c); const reversePairings = Object.entries(pairings).reduce( (acc, [key, [value]]) => (acc[value] = key, acc), {} ); const result = Number.parseInt(output.map((digits) => segmentsOfNums[digits.map((d) => reversePairings[d] ).sort().join('')]).join('')); return sum + result; }, 0)))({ abcefg: 0, cf: 1, acdeg: 2, acdfg: 3, bcdf: 4, abdfg: 5, abdefg: 6, acf: 7, abcdefg: 8, abcdfg: 9 }, document.body.firstChild.textContent.match(/.+\n/g).map( (line) => line.split('|').map(p => p.trim().match(/\w+/g).map((digit) => digit.split(""))))); | |
((get) => document.body.firstChild.textContent.match(/\d/g).map(Number).reduce( (sum, cur, i, a) => (((x,y,g) => (cur < Math.min(g(x-1,y), g(x+1,y), g(x,y-1), g(x,y+1)) ? sum + cur + 1 : sum))(i%100, Math.floor(i/100), (x,y) => get(x,y,a))), 0))((x,y,a) => (x<0||x>99||y<0||y>99) ? Number.MAX_VALUE : a[y*100+x]) | |
((input, get) => input.reduce( (mins, cur, i, a) => ( ( (x,y,g) => ( cur < Math.min( g(x-1,y), g(x+1,y), g(x,y-1), g(x,y+1) ) ? (mins.push([x,y]),mins) : mins ) )( i%100, Math.floor(i/100), (x,y) => get(x,y,a) ) ), [] ).reduce((sizes,min,i,arr) => { sizes.push((function flow(toProcess, seen) { if (toProcess.length === 0) { return 0; } const isIn = ([x0, y0], ...arrs) => arrs.flat().find( ([x, y]) => x === x0 && y === y0 ); const newToProcess = toProcess.reduce( (acc, [x, y]) => { [ [x-1,y], [x+1,y], [x,y-1], [x,y+1] ].forEach( ([xp,yp]) => { const val = input[yp*100+xp]; if ( xp>=0&&xp<=99&&yp>=0&&yp<=99&&val!==9&& !isIn([xp,yp],acc,toProcess,seen) ) { acc.push([xp,yp]); } } ); return acc; }, [] ); seen.push(...toProcess); return toProcess.length + flow(newToProcess,seen); }) ([min], []) ); return sizes; },[]).sort((a,b) => b-a).slice(0,3).reduce((result, cur) => result*cur, 1) ) ( document.body.firstChild.textContent.match(/\d/g).map(Number), (x,y,a) => (x<0||x>99||y<0||y>99) ? Number.MAX_VALUE : a[y*100+x] ); | |
((pairs) => document.body.firstChild.textContent.match(/.+/g).reduce((acc,line) => [...acc, line.split('').reduce((stack,char,i) => (( (open,close) => Array.isArray(stack) ? (open ? (stack.push(char),stack) : (close && stack.pop() === close[0] ? stack : char )) : stack )(pairs.find((pair) => pair[0] === char),pairs.find((pair) => pair[1] === char))), [])], []))([['(',')'],['[',']'],['{','}'],['<','>']]).reduce((points, cur) => ((map) => points + (map[cur] || 0))({')':3,']':57,'}':1197,'>':25137}),0) | |
((points) => points[Math.floor(points.length / 2)])(((pairs) => document.body.firstChild.textContent.match(/.+/g).reduce((acc,line) => [...acc, line.split('').reduce((stack,char,i) => (( (open,close) => Array.isArray(stack) ? (open ? (stack.push(char),stack) : (close && stack.pop() === close[0] ? stack : char )) : stack )(pairs.find((pair) => pair[0] === char),pairs.find((pair) => pair[1] === char))), [])], []))([['(',')'],['[',']'],['{','}'],['<','>']]).reduce((points, stack) => ((map) => [...points, Array.isArray(stack) ? stack.reverse().reduce((ps, cur) => ps*5 + map.indexOf(cur),0): null])(['','(','[','{','<']),[]).filter((a) => a).sort((a,b) => b-a)) | |
((input, forAll, range) => new Array(100).fill(1).reduce((acc,_,i) => { forAll(input, (x,y,oct) => { input[y][x]++; }); const flashed = {}; (function flash(j = 1) { const count = []; forAll(input, (x,y,oct) => { if (oct > 9 && !flashed[x+";"+y]) { flashed[x+";"+y] = true; acc++; range.forEach((dy) => range.forEach((dx) => { if ( !(dx === 0 && dy === 0) && y+dy >= 0 && y+dy < input.length && x+dx >= 0 && x+dx < input[0].length ) { count.push([x+dx,y+dy]); } })) } }); count.forEach(([x,y]) => input[y][x]++); if (count.length) { flash(j+1); } })(); forAll(input, (x,y,oct) => { if (oct > 9) { input[y][x] = 0; } }); return acc; },0))( document.body.firstChild.textContent.match(/.+/g).map((line) => line.match(/\d/g).map(Number)), (arr, cb) => arr.reduce((acc, line, y) => acc + line.reduce((acc2, oct, x) => acc2 + cb(x,y,oct), 0), 0), [-1,0,1]) | |
(([input,allLength], forAll, range) => (function iter(i = 1) { forAll(input, (x,y,oct) => { input[y][x]++; }); const flashed = {}; (function flash(j = 1) { const count = []; forAll(input, (x,y,oct) => { if (oct > 9 && !flashed[x+";"+y]) { flashed[x+";"+y] = true; range.forEach((dy) => range.forEach((dx) => { if ( !(dx === 0 && dy === 0) && y+dy >= 0 && y+dy < input.length && x+dx >= 0 && x+dx < input[0].length ) { count.push([x+dx,y+dy]); } })) } }); count.forEach(([x,y]) => input[y][x]++); if (count.length) { flash(j+1); } })(); forAll(input, (x,y,oct) => { if (oct > 9) { input[y][x] = 0; } }); return Object.keys(flashed).length === allLength ? i : iter(i+1); })())( ((input) => [input, input.flat().length])(document.body.firstChild.textContent.match(/.+/g).map((line) => line.match(/\d/g).map(Number))), (arr, cb) => arr.reduce((acc, line, y) => acc + line.reduce((acc2, oct, x) => acc2 + cb(x,y,oct), 0), 0), [-1,0,1]) | |
((graph) => { const start = graph.find(({name}) => name === "start"); let pathCount = 0; (function recur(node = start, visited = []) { if (node.name === "end") { return pathCount++; } const myVisits = visited.slice(); if (node.visits === 1) { myVisits.push(node); } node.paths.filter((to) => !visited.includes(to)).forEach((to) => recur(to, myVisits)); })(); return pathCount;})(document.body.firstChild.textContent.match(/.+/g).map(line => line.split('-')).reduce( (graph, path) => { const caves = path.map((endPoint, i) => { let cave = graph.find(({name}) => name === endPoint); if (!cave) { cave = { name: endPoint, paths: [], visits: endPoint === endPoint.toUpperCase() ? Infinity : 1 }; graph.push(cave); } return cave; }); caves.forEach((cave, i) => { cave.paths.push(caves[1-i]); }); return graph; }, [])) | |
((graph) => { const start = graph.find(({name}) => name === "start"); let pathCount = 0; (function recur(node = start, visited = [], token = true) { if (node.name === "end") { return pathCount++; } const myVisits = visited.slice(); if (node.visits === 1) { myVisits.push(node); } node.paths.forEach((to) => { if (!visited.includes(to)) { recur(to, myVisits, token); } else if (token && to.name !== "start") { recur(to, myVisits, false); } }) })(); return pathCount;})(document.body.firstChild.textContent.match(/.+/g).map(line => line.split('-')).reduce( (graph, path) => { const caves = path.map((endPoint, i) => { let cave = graph.find(({name}) => name === endPoint); if (!cave) { cave = { name: endPoint, paths: [], visits: endPoint === endPoint.toUpperCase() ? Infinity : 1 }; graph.push(cave); } return cave; }); caves.forEach((cave, i) => { cave.paths.push(caves[1-i]); }); return graph; }, [])) | |
((dots, folds) => dots.reduce( (newDots, dot) => ( (dot[0] < folds[0][1] ? newDots.add(dot.join(";")) : newDots.add( [ dot[0] - (dot[0] - folds[0][1]) * 2, dot[1] ].join(";") ) ), newDots ), new Set() ).size)(...((textContent) => [textContent.match(/\d+,\d+/g).map(l => l.split(',').map(Number)),textContent.match(/\w=\d+/g).map(l =>l.split("=").map((part, i) => i === 1 ? Number(part) : part))])(document.body.firstChild.textContent)) | |
console.log(((dots, folds) => Object.values(folds.reduce((oldDots, fold) => Object.values(oldDots).reduce((newDots, dot) => { const i = ['x','y'].indexOf(fold[0]); const newDot = dot[i] < fold[1] ? dot : [ i === 0 ? dot[0] - (dot[0] - fold[1]) * 2 : dot[0], i === 1 ? dot[1] - (dot[1] - fold[1]) * 2 : dot[1] ]; newDots[newDot.join(";")] = newDot; return newDots; }, {} ), dots )).reduce( (sheet, dot) => { sheet[dot[1]] = sheet[dot[1]] || []; sheet[dot[1]][dot[0]] = "O"; return sheet; }, [] ).map((row) => [...row].map((e) => e || " ").join("")).join('\n'))(...((textContent) => [textContent.match(/\d+,\d+/g).map(l => l.split(',').map(Number)),textContent.match(/\w=\d+/g).map(l =>l.split("=").map((part, i) => i === 1 ? Number(part) : part))])(document.body.firstChild.textContent))) | |
(([template, rules]) => { const counts = Object.values(new Array(10).fill(1).reduce((oldTemplate) => { let newTemplate = ""; oldTemplate.reduce((a, b) => (newTemplate += `${a}${rules.find((rule) => rule[0] === a + b)[1] || ""}`,b) ); return (newTemplate+oldTemplate[oldTemplate.length-1]).split(""); }, template.split("") ).reduce((acc, letter) => (acc[letter] = acc[letter] ? acc[letter] + 1 : 1, acc), {})); return Math.max(...counts) - Math.min(...counts); })( ((textContent) => [textContent.match(/^\w+$/gm)[0], textContent.match(/^\w+ -> \w$/gm).map((line) => line.split(" -> "))])(document.body.firstChild.textContent)) | |
(([template, [rules, counts]]) => { [...template].reduce((a, b) => (counts[a + b]++, b) ); const resultCounts = Object.entries(new Array(40).fill(1).reduce( (oldCounts, i) => { const newCounts = {}; rules.forEach((to, from) => { const count = oldCounts[from] || 0; if (count) { newCounts[to[0]] = (newCounts[to[0]] || 0) + count; newCounts[to[1]] = (newCounts[to[1]] || 0) + count; } }); return newCounts; }, counts )).reduce((acc, [key, count]) => { acc[key[0]] = (acc[key[0]] || 0) + count * 0.5; acc[key[1]] = (acc[key[1]] || 0) + count * 0.5; return acc; }, {}); resultCounts[template[0]] += 0.5; resultCounts[template[template.length-1]] += 0.5; const countValues = Object.values(resultCounts); return Math.max(...countValues) - Math.min(...countValues); })( ((textContent) => [ textContent.match(/^\w+$/gm)[0], textContent.match(/^\w+ -> \w$/gm).reduce( (maps, [...letters]) => { const key = `${letters[0]}${letters[1]}`; const insert = letters.pop(); maps[0].set(key, [`${letters[0]}${insert}`, `${insert}${letters[1]}`]); maps[1][key] = 0; return maps; }, [new Map(), {}] ) ])(document.body.firstChild.textContent)) | |
((input) => { const costs = input.map((line) => new Array(line.length).fill(Infinity)); const paths = input.map((line) => new Array(line.length).fill([])); costs[0][0] = 0; input[0][0] = 0; const end = [input[0].length -1, input.length - 1]; (function process(nodes, visited) { if (!nodes.length) { return; } const thisVisited = [...visited, ...nodes.map(n => n[0] + ";" + n[1])]; const nextNodes = nodes.reduce( (acc, [x0, y0]) => { [[0,1],[1,0],[0,-1],[-1,0]].forEach(([dx,dy]) => { const x1 = x0+dx; const y1 = y0+dy; if (input[y1]?.[x1] === undefined) { return; } const thisCost = costs[y0][x0] + input[y1][x1]; if (thisCost < costs[y1][x1]) { costs[y1][x1] = thisCost; paths[y1][x1] = [...paths[y0][x0], [x1, y1]]; if (!(end[0] === x1 && end[1] === y1)) { acc.push([x1,y1]); } } }); return acc; }, [] ); process(nextNodes, thisVisited); })([[0,0]], []); const endPath = paths[end[1]][end[0]]; const cost = costs[end[1]][end[0]]; return cost; })(document.body.firstChild.textContent.match(/\d+/g).map(([...line]) => line.map(Number))) | |
( (input, offsets) => { const costs = input.map((line) => new Array(line.length).fill(Infinity)); costs[0][0] = 0; input[0][0] = 0; const end = [input[0].length -1, input.length - 1]; function process(nodes) { if (!nodes.length) { return; } const nextNodes = nodes.reduce( (acc, [x0, y0]) => { offsets.forEach(([dx,dy]) => { const x1 = x0+dx; const y1 = y0+dy; if (input[y1]?.[x1] === undefined) { return; } const thisCost = costs[y0][x0] + input[y1][x1]; if (thisCost < costs[y1][x1]) { costs[y1][x1] = thisCost; if (!(end[0] === x1 && end[1] === y1)) { acc.push([x1,y1]); } } }); return acc; }, [] ); return nextNodes; } let inp = [[0,0]]; while(inp.length) { inp = process(inp); } const cost = costs[end[1]][end[0]]; return cost; })( document.body.firstChild.textContent.match(/\d+/g) .map(([...line]) => line.map(Number)) .reduce( (newLines, line, y, lines) => (new Array(5).fill(1).forEach( (_,i) => newLines[i*lines.length + y] = line.reduce( (newLine, item, x, items) => (new Array(5).fill(1).forEach( (_,j) => newLine[j*items.length + x] = ((item + i + j) > 9 ? (item + i + j) - 9 : (item + i + j)) ),newLine), [] ) ),newLines), [] ), [[0,1],[1,0],[0,-1],[-1,0]]) | |
( (input) => ( function step(count = 1) { let moveNum = 0; ['>','v'].forEach((s,j) => { const move = []; input.forEach((line, y) => line.forEach( (c, x) => { if (c === s) { const y1 = j === 1 ? (y === input.length - 1 ? 0 : y + 1) : y; const x1 = j === 0 ? (x === input[0].length - 1 ? 0 : x + 1 ) : x; if (input[y1][x1] === '.') { move.push([x,y,x1,y1]); } } } )); moveNum += move.length; move.forEach(([x0,y0,x1,y1]) => { input[y0][x0] = '.'; input[y1][x1] = s; }); }); if (moveNum > 0) { return step(count+1); } return count; } )() )(document.body.firstChild.textContent.match(/(v|\.|>)+/g).map((line) => line.split(''))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment