Advent-of-Code-2022/6/solution.mjs

33 lines
787 B
JavaScript
Raw Normal View History

2022-12-06 10:38:40 -08:00
import { readFileSync } from 'node:fs';
const input = readFileSync('input', 'utf-8');
function isValidMarker(marker) {
return marker.split('').every((c, i, word) => word.lastIndexOf(c) === i);
}
function findMarker(markerLength) {
for (let pos = markerLength; pos <= input.length; pos++) {
const marker = input.slice(pos - markerLength, pos);
if (isValidMarker(marker)) {
return { marker, pos };
}
}
}
const packetMarker = findMarker(4);
if (packetMarker) {
console.log(
`Found packet marker: ${packetMarker.marker} after: ${packetMarker.pos} ` +
`characters`
);
}
const messageMarker = findMarker(14);
if (messageMarker) {
console.log(
`Found message marker: ${messageMarker.marker} after: ` +
`${messageMarker.pos} characters`
);
}