This commit is contained in:
Yanick Champoux 2021-12-07 10:13:54 -05:00
parent a38fc05fe2
commit 72bcdcd9db
3 changed files with 64 additions and 0 deletions

20
2021/07/part1.mjs Normal file
View File

@ -0,0 +1,20 @@
import fs from "fs-extra";
import fp from "lodash/fp.js";
import _ from "lodash";
export const processInput = (input) => input.split(',').map( x => parseInt(x) );
export function solution(input) {
const min = _.min(input);
const max = _.max(input);
let minScore = 9E99;
for( let i = min; i<= max; i++ ) {
const score = _.sum(input.map( x => Math.abs( x - i ) ));
if( score >= minScore ) break;
minScore = score;
}
return minScore;
}

24
2021/07/part2.mjs Normal file
View File

@ -0,0 +1,24 @@
import fs from "fs-extra";
import fp from "lodash/fp.js";
import _ from "lodash";
import * as p1 from './part1.mjs';
export function solution(input) {
const min = _.min(input);
const max = _.max(input);
let minScore = 9E99;
for( let i = min; i<= max; i++ ) {
const score = _.sum(input.map( x => {
const p = Math.abs( x - i );
if (p==0) return 0;
return p * (p+1) /2
}));
if( score >= minScore ) break;
minScore = score;
}
return minScore;
}

20
2021/07/test.mjs Normal file
View File

@ -0,0 +1,20 @@
// https://adventofcode.com/2021/day/07
import tap from "tap";
import fs from "fs-extra";
import * as p1 from "./part1.mjs";
import * as p2 from "./part2.mjs";
const sample = p1.processInput("16,1,2,0,4,2,7,1,2,14");
const input = fs.readFile("input", "utf8").then(p1.processInput);
tap.test("part1", async (t) => {
t.equal(p1.solution(await sample), 37);
t.equal(p1.solution(await input), 340987);
});
tap.test("part2", async (t) => {
t.equal(p2.solution(await sample), 168);
t.equal(p2.solution(await input), 96987874);
});