From 14efab3450921304c9ab15e8d2836a05fad34277 Mon Sep 17 00:00:00 2001 From: Lewis Dale Date: Fri, 15 Dec 2023 20:46:39 +0000 Subject: [PATCH] Finally do Day Five --- src/day_five.test.ts | 42 ++++++++++++++++++++++++++++++ src/day_five.ts | 61 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 src/day_five.test.ts create mode 100644 src/day_five.ts diff --git a/src/day_five.test.ts b/src/day_five.test.ts new file mode 100644 index 0000000..1e2a637 --- /dev/null +++ b/src/day_five.test.ts @@ -0,0 +1,42 @@ +import {mapSeedToLocation} from "./day_five"; + +describe('Day Five', () => { + const input = `seeds: 79 14 55 13 + +seed-to-soil map: +50 98 2 +52 50 48 + +soil-to-fertilizer map: +0 15 37 +37 52 2 +39 0 15 + +fertilizer-to-water map: +49 53 8 +0 11 42 +42 0 7 +57 7 4 + +water-to-light map: +88 18 7 +18 25 70 + +light-to-temperature map: +45 77 23 +81 45 19 +68 64 13 + +temperature-to-humidity map: +0 69 1 +1 0 69 + +humidity-to-location map: +60 56 37 +56 93 4`; + + it('should calculate the smallest location from the input', () => { + const result = mapSeedToLocation(input); + expect(result).toEqual(46); + }); +}); \ No newline at end of file diff --git a/src/day_five.ts b/src/day_five.ts new file mode 100644 index 0000000..601a59f --- /dev/null +++ b/src/day_five.ts @@ -0,0 +1,61 @@ +import {Range, Seq} from "immutable"; +import {chunk} from "lodash"; +import fs from "fs"; + +type MapRange = { + source: number; + destination: number; + size: number; +} + +const parseSeeds = (input: string): Seq.Indexed => { + const [_, seedString] = input.split('seeds: '); + + return chunk(seedString.split(' '), 2).reduce((seeds, [start, size]) => { + return seeds.concat(Range(Number(start), Number(start) + Number(size))); + }, Seq.Indexed()); +} + +const mapMapper = (input: string): MapRange[] => { + const [_, ...lines] = input.split('\n'); + + return lines.map(line => { + const [dest, source, size] = line.split(' ').map(Number); + return { + source: source, + destination: dest, + size + } + }); +} + +const seedMapper = (seed: number, map: MapRange[]): number => { + const mapped = map.find(({source, destination, size}) => { + return seed >= source && seed < source + size; + }); + + if (!mapped) { + return seed; + } + + return seed - mapped.source + mapped.destination; +} + +export const mapSeedToLocation = (input: string): number => { + const [seedsStr, ...mapStrings] = input.split('\n\n'); + const seeds = parseSeeds(seedsStr); + + const maps = mapStrings.map(mapMapper); + + const mapped = seeds.map(seed => { + return maps.reduce((seed, map) => seedMapper(seed, map), seed); + }); + + return mapped.min()!; +} + +export const runDayFive = () => { + const input = fs.readFileSync('./inputs/day_five_input.txt', 'utf8').trimEnd(); + const result = mapSeedToLocation(input); + console.log(`Day Five: ${result}`); +} \ No newline at end of file