
Day 5, part 1
Day 5 challenge of the mighty Advent of Code 2024
Introduction
Hello there! I would like to kindly invite you to the day 5 of Advent of Code. As always please read and understand the puzzle before following the rest of the article. The whole description of today's puzzle can be found here. Today we are asked to do some data transformations based on mapping data. We are given the input text file which includes the list of seeds numbers which are our initial inputs and the rest of the file is describing number of transformations to be done, where each transformation takes as the input, the output of the previous one. Finally, from the list of the transformations outputs, we need to find the lowest location number, which is the answer to the puzzle.
Creating files for the challenge
We are going to start by creating the new directory day-5 in or project's root directory. We also create new main.js file inside the day-5 folder, which will be our main entry for the code for this puzzle.
We can also put the test input data.
1const input = `seeds: 79 14 55 13
2seed-to-soil map:
350 98 2
452 50 48
5soil-to-fertilizer map:
60 15 37
737 52 2
839 0 15
9fertilizer-to-water map:
1049 53 8
110 11 42
1242 0 7
1357 7 4
14water-to-light map:
1588 18 7
1618 25 70
17light-to-temperature map:
1845 77 23
1981 45 19
2068 64 13
21temperature-to-humidity map:
220 69 1
231 0 69
24humidity-to-location map:
2560 56 37
2656 93 4`;Solution
To solve the puzzle we need to do the following steps:
- Parse the input data to get
seedsandmaps. - Perform mapping on the inputs to get the outputs.
- Chain these transformations starting with the
seedas an initial input for the first transformation and then passing the output as an input to the next transformation. - In the transformations results, find the lowest
location.
Parsing the data
Before we can do any magic to get the expected results, we first have to transform the input text data into something more useful. We need to extract the seeds data and data for each map. Here is the piece of code that handles parsing the seeds.
1function parseData(input) {
2 const [seedBlock, ...mapBlocks] = textToBlocks(input);
3 const seeds = getSeeds(seedBlock);
4 return { seeds };
5}
6function textToBlocks(text) {
7 return text.split('\
8\
9');
10}
11function getSeeds(seedsString) {
12 const [, seeds] = seedsString.split(':');
13 return numberTextToInts(seeds);
14}
15function numberTextToInts(numbersString) {
16 const strings = numbersString.trim().split(' ');
17 return strings.map((seed) => parseInt(seed));
18}
19const inputData = parseData(input);
20console.log(inputData);Running this will give us the following:
1{
2 seeds: [ 79, 14, 55, 13 ]
3}As you can see we have nice array of parsed digits.
Now it's time for parsing the maps data.
For each map the interesting data is name of the map, mapData as the arrays with numbers and what I think might be useful, the first part of the next maps name. As we see in the test data, the name of each map is built of three words connected with dashes. The last piece of every map name is the starting piece of the next map.
1function parseData(input) {
2 const [seedBlock, ...mapBlocks] = textToBlocks(input);
3 const seeds = getSeeds(seedBlock);
4 const maps = mapBlocks.map(getMap);
5 return { seeds, maps };
6}
7...
8function getMap(mapString) {
9 const [stringWithName, ...mapNumbers] = mapString.split("\
10");
11 const name = getMapName(stringWithName);
12 const nextMap = getNextMap(name);
13 const mapData = mapNumbers.map(numberTextToInts);
14 return { name, nextMap, mapData };
15}
16function getMapName(stringIncludingMapName) {
17 return stringIncludingMapName.split(" map:")[0];
18}
19function getNextMap(mapName) {
20 return mapName.split("-")[2];
21}The above pieces of code added to that we had, gives us these results:
1{
2 seeds: [ 79, 14, 55, 13 ],
3 maps: [
4 { name: 'seed-to-soil', nextMap: 'soil', mapData: [Array] },
5 {
6 name: 'soil-to-fertilizer',
7 nextMap: 'fertilizer',
8 mapData: [Array]
9 },
10 { name: 'fertilizer-to-water', nextMap: 'water', mapData: [Array] },
11 { name: 'water-to-light', nextMap: 'light', mapData: [Array] },
12 {
13 name: 'light-to-temperature',
14 nextMap: 'temperature',
15 mapData: [Array]
16 },
17 {
18 name: 'temperature-to-humidity',
19 nextMap: 'humidity',
20 mapData: [Array]
21 },
22 {
23 name: 'humidity-to-location',
24 nextMap: 'location',
25 mapData: [Array]
26 }
27 ]
28}As you can see the output in terminal is truncated so I added console.log(inputData.maps[0]); to get the insights how the data really looks like.
1{
2 name: 'seed-to-soil',
3 nextMap: 'soil',
4 mapData: [ [ 50, 98, 2 ], [ 52, 50, 48 ] ]
5}As you can see we have all the data we might need. We can now start to solve the puzzle.
1git add .
2git commit -m "parse input data"Calculating map output
All the operations we need to do, are basically transformations of the input, into the output data based on the numbers in the map. Each transformation is divided to couple of operations:
- We first change the representation of the map data from array of numbers to objects with descriptive properties (this is totally optional, I did this only to make things easier to follow).
- We check if the input is in any of the map ranges:
- if it is not, the output of the mapping is just the input itself
- if the input is in one of the ranges, we take this range we do the calculations
- We calculate the output by measuring distance from the source range start and we add this distance to the destination range start. From the puzzle description we can take the example outputs for the
seed-to-soilmap:
10 -> 0
21 -> 1
3... ...
448 -> 48
549 -> 49
650 -> 52
751 -> 53
8... ...
996 -> 98
1097 -> 99
1198 -> 50
1299 -> 51And this is the code which does that:
1function performMapTranformation(input, map) {
2 const { mapData } = map;
3 const mapObjects = mapData.map(mapDataArrayToObject);
4 return getMapOutput(input, mapObjects);
5}
6function mapDataArrayToObject(map) {
7 return {
8 destRangeStart: map[0],
9 sourceRangeStart: map[1],
10 rangeLength: map[2],
11 };
12}
13function getMapOutput(input, mapObjects) {
14 const fittingRange = getFittingRange(input, mapObjects);
15 if (!fittingRange) {
16 return input;
17 }
18 const distance = input - fittingRange.sourceRangeStart;
19 return fittingRange.destRangeStart + distance;
20}
21function getFittingRange(input, mapObjects) {
22 return mapObjects.find(
23 (map) => input >= map.sourceRangeStart && input < map.sourceRangeStart + map.rangeLength
24 );
25}
26const testSeeds = [0, 1, 10, 48, 49, 50, 51, 96, 97, 98, 99];
27testSeeds.forEach((seed) => {
28 const firstMapOutput = performMapTranformation(seed, inputData.maps[0]);
29 console.log(`Map output for ${seed} is ${firstMapOutput}`);
30});I have declared the testSeeds with the example numbers and run the first map transformation on each of them.
1Map output for 0 is 0
2Map output for 1 is 1
3Map output for 10 is 10
4Map output for 48 is 48
5Map output for 49 is 49
6Map output for 50 is 52
7Map output for 51 is 53
8Map output for 96 is 98
9Map output for 97 is 99
10Map output for 98 is 50
11Map output for 99 is 51Seems to work as expected. Good job! It is a great time to save our progress.
Chaining the maps
We now have a way to perform transformations for each single map, but now we have to figure out how to order these transformations and run them one by one feeding the output of the previous transformation, to the next one. We can either store these maps in an iterator object which will have methods like next and properties like done which allow you to iterate through the elements. We can also just sort the array of maps based on the nextMap property.
1function sortMaps(mapA, mapB) {
2 if (mapB.name.startsWith(mapA.nextMap)) {
3 return -1;
4 }
5 return 1;
6}
7const sortedMaps = inputData.maps.sort(sortMaps);
8console.log('Sorted maps: ', sortedMaps);And the results are as follow:
1Sorted maps: [
2 {
3 name: 'seed-to-soil',
4 nextMap: 'soil',
5 mapData: [ [Array], [Array] ]
6 },
7 {
8 name: 'soil-to-fertilizer',
9 nextMap: 'fertilizer',
10 mapData: [ [Array], [Array], [Array] ]
11 },
12 {
13 name: 'fertilizer-to-water',
14 nextMap: 'water',
15 mapData: [ [Array], [Array], [Array], [Array] ]
16 },
17 {
18 name: 'water-to-light',
19 nextMap: 'light',
20 mapData: [ [Array], [Array] ]
21 },
22 {
23 name: 'light-to-temperature',
24 nextMap: 'temperature',
25 mapData: [ [Array], [Array], [Array] ]
26 },
27 {
28 name: 'temperature-to-humidity',
29 nextMap: 'humidity',
30 mapData: [ [Array], [Array] ]
31 },
32 {
33 name: 'humidity-to-location',
34 nextMap: 'location',
35 mapData: [ [Array], [Array] ]
36 }
37]Now the second part is to go through these maps and perform their transformations to get the final results for each seed.
Before I show you the code and its output, here are the expected results for the seeds we are getting from the test data (this comes straight from the website):
1- Seed 79, soil 81, fertilizer 81, water 81, light 74, temperature 78, humidity 78, location 82.
2- Seed 14, soil 14, fertilizer 53, water 49, light 42, temperature 42, humidity 43, location 43.
3- Seed 55, soil 57, fertilizer 57, water 53, light 46, temperature 82, humidity 82, location 86.
4- Seed 13, soil 13, fertilizer 52, water 41, light 34, temperature 34, humidity 35, location 35.And the code which does that is:
1function getMapsOutputs(input, maps) {
2 const results = [input];
3 let currentInput = input;
4 maps.forEach((map) => {
5 const output = performMapTranformation(currentInput, map);
6 results.push(output);
7 currentInput = output;
8 });
9 return results;
10}
11const mapOutputs = inputData.seeds.map((seed) => getMapsOutputs(seed, sortedMaps));
12console.log('Transformations results: ', mapOutputs);1Transformations results: [
2 [ 79, 81, 81, 81, 74, 78, 78, 82 ],
3 [ 14, 14, 53, 49, 42, 42, 43, 43 ],
4 [ 55, 57, 57, 53, 46, 82, 82, 86 ],
5 [ 13, 13, 52, 41, 34, 34, 35, 35 ]
6]Look's that we get the right results, so we can now commit the changes.
1git add .
2git commit -m "find mapping outputs"Finding the lowest location
The final step is to find the lowest location and return it as a final result. The location is a last element in each transformations outputs.
1function findLowestLocation(mapOutputs) {
2 const transformationsChainLastIndex = mapOutputs[0].length - 1;
3 let lowestLocation = mapOutputs[0][transformationsChainLastIndex];
4 mapOutputs.forEach((mapOutput) => {
5 if (mapOutput[transformationsChainLastIndex] < lowestLocation) {
6 lowestLocation = mapOutput[transformationsChainLastIndex];
7 }
8 });
9 return lowestLocation;
10}
11const lowestLocation = findLowestLocation(mapOutputs);
12console.log('Lowest location: ', lowestLocation);We can see in the puzzle description that for our test data the lowest locations is 35. We can run our code and find out if we did everything correctly.
1Lowest location: 35Success!
Let's save the changes and try our code on the real input data.
1git add .
2git commit -m "find lowest location"Final result
This is the time to test our code in battle. Once again we will use the readFile function, to get the real input data, which we copy from the Advent of Code website and we put the data inside input.txt file.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');Now we run the code and we can see in the terminal:
1Lowest location: 579439039After submitting the result, we can see the message that we were RIGHT! Great work everyone!
We can now save the final result.
1git add .
2git commit -m "day 5 part 1 final result"Now its time to beat the part two., so see you all in Day 5, part 2!