Skip to content

Instantly share code, notes, and snippets.

@laqie
Last active December 7, 2024 13:57
Show Gist options
  • Select an option

  • Save laqie/e79ec759d9529e16cc7db5a74cfbc2ad to your computer and use it in GitHub Desktop.

Select an option

Save laqie/e79ec759d9529e16cc7db5a74cfbc2ad to your computer and use it in GitHub Desktop.
AoC 2024 Day 7
CPU | Intel(R) Core(TM) i5-8400 CPU @ 2.80GHz
Runtime | Deno 2.1.3 (x86_64-pc-windows-msvc)
benchmark time/iter (avg) iter/s (min … max) p75 p99 p995
----------------------- ----------------------------- --------------------- --------------------------
group part one
part one 382.0 µs 2,618 (358.9 µs … 964.1 µs) 376.7 µs 536.0 µs 574.4 µs
part one with parsing 1.4 ms 737.2 ( 1.3 ms … 1.9 ms) 1.4 ms 1.7 ms 1.9 ms
summary
part one
3.55x faster than part one with parsing
group part two
part two 715.2 µs 1,398 (672.3 µs … 1.1 ms) 708.3 µs 930.1 µs 978.6 µs
part two with parsing 1.7 ms 579.2 ( 1.6 ms … 2.7 ms) 1.7 ms 2.2 ms 2.4 ms
summary
part two
2.41x faster than part two with parsing
import $ from '@david/dax';
import * as S from '@utils/string.ts';
import * as A from 'effect/Array';
import { pipe } from 'effect/Function';
type Equation = {
result: number;
numbers: number[];
};
function parseEquation(line: string): Equation {
const [result, numbers] = line.split(':');
return {
result: Number(result),
numbers: numbers.trim().split(' ').map(Number),
};
}
function parse(input: string) {
return pipe(
input,
S.splitByEol,
A.map(parseEquation),
);
}
function substract(a: number, b: number): [number, number] {
let e = 1;
while (e <= b) e *= 10;
return [Math.trunc(a / e), a % e];
}
function isPossibleReverse({result, numbers}: Equation, withConcatenate = false): number {
if (numbers.length === 0) return 0;
const _isPossible = (result: number, idx = numbers.length - 1): boolean => {
if (idx < 0) return result === 0;
const n = numbers[idx];
if (result % n === 0 && _isPossible(result / n, idx - 1)) return true;
if (_isPossible(result - n, idx - 1)) return true;
if (withConcatenate) {
const [a, b] = substract(result, n);
if (b === n) return _isPossible(a, idx - 1);
}
return false;
};
return _isPossible(result) ? result : 0;
}
export function getPartOneAnswer(input: string) {
return pipe(
input,
parse,
A.map(e => isPossibleReverse(e)),
A.reduce(0, (a, b) => a + b),
);
}
export function getPartTwoAnswer(input: string) {
return pipe(
input,
parse,
A.map(e => isPossibleReverse(e, true)),
A.reduce(0, (a, b) => a + b),
);
}
export const inputFile = 'input.txt';
if (import.meta.main) {
const input = await $
.path(import.meta.dirname!)
// .resolve('input2.txt')
.resolve(inputFile)
.readText();
const partOneAnswer = getPartOneAnswer(input);
console.log(partOneAnswer);
const partTwoAnswer = getPartTwoAnswer(input);
console.log(partTwoAnswer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment