main
Yanick Champoux 2022-12-13 12:58:12 -05:00
parent c4f0e4f606
commit f4553810c1
4 changed files with 119 additions and 0 deletions

46
2022/13/part1.js Normal file
View File

@ -0,0 +1,46 @@
import * as R from "remeda";
import { readFile } from "../05/part1.js";
const readInput = (...args) =>
R.pipe(
readFile(...args),
(lines) => lines.split("\n\n"),
R.compact, // remove last line
R.map(
block => block.split("\n").map( line => eval(line) )
)
);
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
export function isLessThan(x,y) {
if( [x,y].every(R.isNumber) ) return x < y ? -1 : x == y ? 0 : 1;
if( [x,y].every(R.isArray) ) {
for ( const [a,b] of R.zip(x,y)) {
const res = isLessThan(a,b);
if(res !== 0) return res;
}
if( x.length === y.length ) return 0
return x.length < y.length ? -1 : 1;
}
return isLessThan(...[x,y].map( z => R.isNumber(z)? [z] : z ));
}
const passthru = (x) => (arg) => {
x(arg);
return arg;
}
export default R.createPipe(
R.map( ([x,y]) => isLessThan(x,y) ),
(results) => results.map(
(value,index) => ({ value, index: index+1 })
),
R.filter( ({ value }) => value !== 1 ),
R.map( R.prop('index') ),
(results) => results.reduce((a,b) => a+b)
);

13
2022/13/part2.js Normal file
View File

@ -0,0 +1,13 @@
import * as R from "remeda";
import { isLessThan } from "./part1";
const dividers = [[[2]],[[6]]];
export default R.createPipe(
R.flatten,
R.concat(dividers),
(packets) => packets.sort(isLessThan),
packets => packets.map( (p,i) => ({ i: i+1, divider: dividers.includes(p) }) ),
R.filter( ({divider}) => divider ),
R.map(R.prop('i')),
(v) => v.reduce((a,b)=>a*b),
);

23
2022/13/sample Normal file
View File

@ -0,0 +1,23 @@
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]

37
2022/13/test.js Normal file
View File

@ -0,0 +1,37 @@
import { test, expect, describe } from "vitest";
import { expectSolution } from "../01/main.js";
import part1, { sample, puzzleInput, isLessThan } from "./part1.js";
import part2 from "./part2.js";
describe("part 1", () => {
test( "readInput", () => {
expect(sample[0][0]).toEqual([1,1,3,1,1]);
});
test( "lessThan", () => {
expect( isLessThan(1,2) ).toBe(-1);
expect( isLessThan(2,1) ).toBe(1);
expect( isLessThan(2,2) ).toBe(0);
expect( isLessThan(2,[1]) ).toBe(1);
expect( isLessThan([1],[2]) ).toBe(-1);
});
test("sample", () => {
expect(part1(sample)).toEqual(13);
});
test("solution", () => {
const r = part1(puzzleInput);
expect(r).toBeGreaterThan(435);
expect(r).toBeLessThan(10980);
expectSolution(r).toEqual(5806);
});
});
describe("part 2", () => {
test("sample", () => {
expect(part2(sample)).toEqual(140);
});
test("solution", () => {
expectSolution(part2(puzzleInput)).toEqual(23600);
});
});