Finally do Day Five

This commit is contained in:
Lewis Dale 2023-12-15 20:46:39 +00:00
parent 835e507816
commit 14efab3450
2 changed files with 103 additions and 0 deletions

42
src/day_five.test.ts Normal file
View File

@ -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);
});
});

61
src/day_five.ts Normal file
View File

@ -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<number> => {
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<number>());
}
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}`);
}