This commit is contained in:
Leonard Lorenz 2025-12-03 00:03:41 +01:00
parent 4fba52d596
commit 048cc9d4c2

View file

@ -3,19 +3,17 @@ import { solvables } from "../main.ts";
import type { Solvable } from "../solvable.ts"; import type { Solvable } from "../solvable.ts";
import { readInput } from "../utils.ts"; import { readInput } from "../utils.ts";
const checkWindow = (input: number): boolean => {
// check if pattern with given width repeats in input const width = String(input).length / 2
const checkWindow = (width: number, input: number): boolean => {
const str = String(input); const str = String(input);
for (let patternStart = 0; patternStart + 2 * width < str.length; patternStart += width) {
const leftPatIdx = [patternStart, patternStart + width] const leftPatIdx = [0, width]
const rightPatIdx = [patternStart + width, patternStart + width + width] const rightPatIdx = [width, width + width]
const patternRepeated = str.slice(...leftPatIdx) === str.slice(...rightPatIdx);
if (patternRepeated) { const left = str.slice(...leftPatIdx)
return true; const right = str.slice(...rightPatIdx);
}
} return left === right;
return false
} }
class DayTwo implements Solvable { class DayTwo implements Solvable {
@ -24,23 +22,17 @@ class DayTwo implements Solvable {
public part1(): DayTwo { public part1(): DayTwo {
const vals: [number, number][] = this.input const vals: [number, number][] = this.input
.split(",") .split(",")
.map(range => range.split("-") .map(range => range.trim().split("-")
.map(Number) as [number, number]); .map(Number) as [number, number]);
const invalid: number[] = []; const invalid: number[] = [];
for (const [start, end] of vals) { for (const [start, end] of vals) {
for (let i = start; i <= end; i++) { for (let i = start; i <= end; i++) {
// if the number is of odd length, it can't have a repeating pattern if (String(i).length % 2 === 1) continue
if (String(i).length % 2 !== 0) { if (checkWindow(i)) {
continue; console.log(i)
} invalid.push(i);
// check for patterns with increasing width but never exceeding half the length of the number
for (let width = 2; width <= String(i).length / 2; width++) {
if (checkWindow(width, i)) {
invalid.push(i);
break;
}
} }
} }
} }