From 72bcdcd9dbeb51dec4ceb32b149145f212908a31 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Tue, 7 Dec 2021 10:13:54 -0500 Subject: [PATCH] 2021-07 --- 2021/07/part1.mjs | 20 ++++++++++++++++++++ 2021/07/part2.mjs | 24 ++++++++++++++++++++++++ 2021/07/test.mjs | 20 ++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 2021/07/part1.mjs create mode 100644 2021/07/part2.mjs create mode 100644 2021/07/test.mjs diff --git a/2021/07/part1.mjs b/2021/07/part1.mjs new file mode 100644 index 0000000..a976f79 --- /dev/null +++ b/2021/07/part1.mjs @@ -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; +} diff --git a/2021/07/part2.mjs b/2021/07/part2.mjs new file mode 100644 index 0000000..955ff2d --- /dev/null +++ b/2021/07/part2.mjs @@ -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; +} diff --git a/2021/07/test.mjs b/2021/07/test.mjs new file mode 100644 index 0000000..592e086 --- /dev/null +++ b/2021/07/test.mjs @@ -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); +});