45 lines
1.6 KiB
TypeScript
45 lines
1.6 KiB
TypeScript
const input = Deno.readTextFileSync('./input.txt').trimEnd();
|
|
|
|
function findMsgFrame(stream: string, messageLength: number) {
|
|
for (let index = messageLength; index < stream.length; index++) {
|
|
const frame = new Set(stream.slice(index - messageLength, index));
|
|
if (frame.size === messageLength) return index;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
function findMsgSlidingFrame(stream: string, messageLength: number) {
|
|
const frame: Record<string, number> = {};
|
|
for (let index = 0; index < stream.length; index++) {
|
|
const charAdd = stream[index];
|
|
frame[charAdd] = charAdd in frame ? ++frame[charAdd] : 1;
|
|
|
|
const charRemove = stream[index - messageLength];
|
|
const count = frame[charRemove];
|
|
if (count > 1) frame[charRemove] = --frame[charRemove];
|
|
else delete frame[charRemove];
|
|
|
|
if (Object.keys(frame).length === messageLength) return ++index;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
function findMsgRegex(stream: string, messageLength: number) {
|
|
let re = '(.)';
|
|
const backRefs = [];
|
|
for (let i = 1; i < messageLength; i++) {
|
|
backRefs.push(`\\${i}`);
|
|
re += `(.)(?<!${backRefs.join('|')})`;
|
|
}
|
|
const match = stream.match(new RegExp(re));
|
|
return match?.index ? match.index + messageLength : -1;
|
|
}
|
|
|
|
console.log('Frame Solution Part 1:\t\t', findMsgFrame(input, 4));
|
|
console.log('Sliding Frame Solution Part 1:\t', findMsgSlidingFrame(input, 4));
|
|
console.log('RegEx Solution Part 1:\t\t', findMsgRegex(input, 4), '\n');
|
|
|
|
console.log('Frame Solution Part 2:\t\t', findMsgFrame(input, 14));
|
|
console.log('Sliding Frame Solution Part 2:\t', findMsgSlidingFrame(input, 14));
|
|
console.log('RegEx Solution Part 2:\t\t', findMsgRegex(input, 14));
|