generated from eric/adventofcode2023
66 lines
1.7 KiB
JavaScript
66 lines
1.7 KiB
JavaScript
import { readFileSync } from 'node:fs';
|
|
|
|
// const inputArray = readFileSync('sample.txt').toString().split(",");
|
|
const inputArray = readFileSync('input.txt').toString().split(",");
|
|
|
|
// Part One
|
|
console.time("part1");
|
|
let sum = 0;
|
|
|
|
for (const element of inputArray) {
|
|
const contents = element.split("-");
|
|
const start = Number.parseInt(contents[0]);
|
|
const end = Number.parseInt(contents[1]);
|
|
|
|
for (let sku = start; sku <= end; sku++) {
|
|
const skuString = sku.toString();
|
|
const digits = skuString.length
|
|
if (digits % 2 === 0) {
|
|
if (skuString.slice(0, digits / 2) === skuString.slice(digits / 2)) {
|
|
sum += sku;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
console.timeEnd("part1");
|
|
console.log(sum);
|
|
|
|
|
|
// Part Two
|
|
|
|
console.time("part2");
|
|
let sum2 = 0;
|
|
const repeats = [];
|
|
|
|
for (const element of inputArray) {
|
|
const contents = element.split("-");
|
|
const start = Number.parseInt(contents[0]);
|
|
const end = Number.parseInt(contents[1]);
|
|
|
|
for (let sku = start; sku <= end; sku++) {
|
|
const skuString = sku.toString();
|
|
const digits = skuString.length
|
|
const maxRepeatLength = Math.floor(digits / 2);
|
|
for (let repeatLength = 1; repeatLength <= maxRepeatLength; repeatLength++) {
|
|
if (digits % repeatLength === 0) {
|
|
const maxRepeats = digits / repeatLength;
|
|
const repeatPattern = skuString.slice(0, repeatLength);
|
|
const repeatedPattern = repeatPattern.repeat(maxRepeats);
|
|
if (repeatedPattern === skuString) {
|
|
repeats.push(sku);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const uniqueRepeats = [...new Set(repeats)];
|
|
|
|
for (const repeat of uniqueRepeats) {
|
|
sum2 += Number.parseInt(repeat);
|
|
}
|
|
console.timeEnd("part2");
|
|
console.log(sum2);
|
|
|
|
// functions
|