advent of code 2023 day 5

This commit is contained in:
Wouter Groeneveld 2023-12-05 14:05:16 +01:00
parent 829902ee39
commit 3de76649c8
4 changed files with 117 additions and 0 deletions

41
2023/05/impl.js Normal file
View File

@ -0,0 +1,41 @@
module.exports.solve = function(input) {
const toNrs = line => line.split(' ').map(nr => parseInt(nr))
const range = (from, size) => [...Array(size).keys()].map(x => x + from)
// line 1: seeds. line 3: seed-to-soil. after an empty line: next map
const lines = input.split('\n')
const seeds = toNrs(lines.splice(0, 2)[0].replace("seeds: ", ""))
const toGardenMap = (lines) => {
const map = {}
let currentKey = ""
lines.forEach(line => {
if(line.indexOf("map:") > 0) {
currentKey = line.replace(" map:", "")
map[currentKey] = []
} else if(line.length > 2) {
// e.g. 50 98 2; destination range 50, source range start 98, range length 2
const nrs = toNrs(line)
map[currentKey].push({
src: range(nrs[1], nrs[2]),
dest: range(nrs[0], nrs[2])
})
}
})
return map
}
const map = toGardenMap(lines)
const toLocation = (seed) => {
let next = seed;
for(step of ['seed-to-soil', 'soil-to-fertilizer', 'fertilizer-to-water', 'water-to-light', 'light-to-temperature', 'temperature-to-humidity', 'humidity-to-location']) {
const curr = next
const foundConv = map[step].find(conv => conv.src.indexOf(next) !== -1)
if(foundConv) next = foundConv.dest[foundConv.src.indexOf(next)]
}
return next
}
return seeds.map(toLocation).sort()[0]
}

33
2023/05/input.txt Normal file
View File

@ -0,0 +1,33 @@
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

1
2023/05/output.txt Normal file
View File

@ -0,0 +1 @@
35

42
2023/05/test.js Normal file
View File

@ -0,0 +1,42 @@
const test = require('node:test')
const assert = require('node:assert').strict;
const { readFileSync } = require('fs')
const { solve } = require('./impl.js')
test('Seeds to location mapping works and lowest location is 35', (t) => {
const input = readFileSync('input.txt').toString()
const expected_output = parseInt(readFileSync('output.txt').toString())
const out = solve(input)
assert.equal(out, expected_output)
})
test('No number sequence found means taking the same number during all steps', (t) => {
const expected_output = 10
const input = `seeds: 10 20 30
seed-to-soil map:
1 2 2
soil-to-fertilizer map:
1 2 2
fertilizer-to-water map:
1 2 2
water-to-light map:
1 2 2
light-to-temperature map:
1 2 2
temperature-to-humidity map:
1 2 2
humidity-to-location map:
1 2 2`
const out = solve(input)
assert.equal(out, expected_output)
})