
Day 1, part 1
Day 1 challenge of the mighty Advent of Code 2024
Introduction
Just to mention before we get started - all the challenges I will be solving using JavaScript, as this is the language I'm mainly using in my day to day work. The first day challenge can be found here. Read the description carefully to understand the problem we want to solve. Basically we are asked to find the first and the last digit in each of the given strings of input data. Next we are asked to combine these two digits to create a number. Finally, to get the final result of this challenge we need to sum up all the numbers together. This is the answer to this puzzle which we then will be submitting on the web page and if we get the correct one we will receive a star and we will be able to move forward. So let's jump right into it.
Understanding the problem
Let's have look at the example data:
11abc2
2pqr3stu8vwx
3a1b2c3d4e5f
4treb7uchetNow getting the first digit and the last one of each of these strings, and making the number out of them, gives us these values: 12, 38, 15 and 77. The final result after adding them together is 142.
So how can we achieve this in code? Let's try to divide the problem into smaller pieces which we can then combine together.
Preparing the coding environment
I like to keep thing organised and structured and I recommend you to do the same, this way it's easy to navigate throughout the files and find what we are looking for, even long time after we are done.
I made a project folder named advent-of-code-2023 and inside a next one called day-1. The main file we are be working in is named main.js.
Also I always like to keep things under version control so using the terminal I initialize git.
1git initThis way we can commit changes we make and keep track of our progress. We can even push our changes to remote repository on GitHub (what I will do so you will have access to the solutions I've done). The project structure in VSCode looks like this:
Solution
Preparing the input data
First lets start by copying the test data and keep it in a variable.
1const input = `1abc2
2pqr3stu8vwx
3a1b2c3d4e5f
4treb7uchet`;We start with test data before we move to the real one, because this way we can be sure that we get the results we want. Next to be able to search for digits in each line of text we have to split the text into separate lines. Let's build a function to do so. and use it to get an array of strings.
1function textToLinesArray(text) {
2 return text.split('\
3');
4}
5const inputLines = textToLinesArray(input);
6console.log('Array of strings: ', inputLines);I put the console log at the end so we can now run the script and see if we get what we wanted. In the terminal I navigate to our day-1 directory and run the main.js script.
1cd day-1
2node main.jsAnd the result we see in the console is the following:
1Array of strings: [ '1abc2', 'pqr3stu8vwx', 'a1b2c3d4e5f', 'treb7uchet' ]Finding the first digit
Now lets think of how can we can get the first digit in each string. As this is just a single digit, we can go through each character in the string and check if this character is a number.
To do so we need a way to recognize a digit.
1function isCharADigit(char) {
2 return !isNaN(parseInt(char));
3}This function is first trying to parse a number of the given character and then check if the result is a NaN, then we inverse the output to get what we are looking for. Now lets test the output by looping over the first string of input.
1const characters = inputLines[0].split('');
2characters.forEach((line) => console.log(`${line} -> ${isCharADigit(line)}`));This gives us the results we expected.
11 -> true
2a -> false
3b -> false
4c -> false
52 -> trueHow we can now use this to find the first digit in the string? Let's continue again just by looking at the first string we have. We can create a function that goes through every char in a loop and returns the first digit it finds.
1function getFirstDigitInString(string) {
2 const chars = string.split('');
3 for (let i = 0; i < chars.length; i++) {
4 const char = chars[i];
5 if (isCharADigit(char)) {
6 return parseInt(char);
7 }
8 }
9 throw new Error('No digits found');
10}
11const firstDigitOfFirstLine = getFirstDigitInString(inputLines[0]);
12console.log('First digit of the first line: ', firstDigitOfFirstLine);As you can see, our function simply takes any string, breaks it into array of characters, goes through them in the loop and returns a parsed number as soon as it finds any, also breaking out of the loop. If for whatever reason there is no digit we can throw an error for now. I also put some code to view the results for the first line of our test data. Running now out script gives us following result:
1First digit of the first line: 1Finding the last digit
Now lets think, how can we do the same for the last digit. The most obvious way would be to do the same operation we do for the first digit but looping backwards.
1function getLastDigitInString(string) {
2 const chars = string.split('');
3 for (let i = chars.length - 1; i >= 0; i--) {
4 const char = chars[i];
5 if (isCharADigit(char)) {
6 return parseInt(char);
7 }
8 }
9 throw new Error('No digits found');
10}
11const lastDigitOfFirstLine = getLastDigitInString(inputLines[0]);
12console.log('Last digit of the first line: ', lastDigitOfFirstLine);Running this code displays this message in the console:
1Last digit of the first line: 2Seems to work fine.
Getting the calibration value
Now we need to combine this two into a number. In the challenge these numbers are called the "calibration values". I will using these convention to name our next function.
1function getCalibrationValueFromString(string) {
2 const firstDigit = getFirstDigitInString(string);
3 const lastDigit = getLastDigitInString(string);
4 return firstDigit * 10 + lastDigit;
5}
6const firstCalibrationValue = getCalibrationValueFronString(inputLines[0]);
7console.log('First calibration value is: ', firstCalibrationValue);This function simply makes a use of the two other function we built and combine the result into a single number.
1First calibration value is: 12Lets now try to loop over the test data and see if all the values we get are the values we expect.
1const calibrationValues = inputLines.map(getCalibrationValueFromString);
2console.log('Calibration values: ', calibrationValues);Running the script again logs the following:
1Calibration values: [ 12, 38, 15, 77 ]what matches the values we expected.
The final thing will be to sum this results up and check if we get the expected output.
1const result = calibrationValues.reduce((acc, curr) => acc + curr, 0);
2console.log('Final result is: ', result);Ant we get back the message:
1Final result is: 142which is exactly what we were looking for.
Refactoring
Having all these pieces together we have almost everything to finish the first part of the day 1 challenge. But before we run our code on the real input data, it would be nice to have everything cleaned up and properly structured.
But before we do so lets commit the changes we have so far in case we would like to get back to it someday in the future.
1git add .
2git commit -m "working code for test data"I decided that I want to have one function that we run with one param which is text data. This function combines all the functionalities we have to build the final result which is the single number representing the sum of all calibration values.
1const input = `1abc2
2pqr3stu8vwx
3a1b2c3d4e5f
4treb7uchet`;
5function getCalibrationValues(text) {
6 const lines = textToLinesArray(text);
7 const calibrationValues = lines.map(getCalibrationValueFromString);
8 const result = sumNumberArray(calibrationValues);
9 return result;
10}
11function textToLinesArray(text) {
12 return text.split('\
13');
14}
15function getCalibrationValueFromString(string) {
16 const firstDigit = getFirstDigitInString(string);
17 const lastDigit = getLastDigitInString(string);
18 return firstDigit * 10 + lastDigit;
19}
20function getFirstDigitInString(string) {
21 const chars = string.split('');
22 for (let i = 0; i < chars.length; i++) {
23 const char = chars[i];
24 if (isCharADigit(char)) {
25 return parseInt(char);
26 }
27 }
28 throw new Error('No digits found');
29}
30function getLastDigitInString(string) {
31 const chars = string.split('');
32 for (let i = chars.length - 1; i >= 0; i--) {
33 const char = chars[i];
34 if (isCharADigit(char)) {
35 return parseInt(char);
36 }
37 }
38 throw new Error('No digits found');
39}
40function isCharADigit(char) {
41 return !isNaN(parseInt(char));
42}
43function sumNumberArray(numbers) {
44 return numbers.reduce((acc, curr) => acc + curr, 0);
45}
46console.log('Callibration sum is: ', getCalibrationValues(input));This script when run still gives us the correct answer but now its clean and easy to follow. Again, we can commit the changes now to keep this version of our code safe.
1git add .
2git commit -m "refactor the code"Real input data
The final step to solve the first part of the day 1 challenge is to use the real input data provided on the day 1 page. I created the input.txt file inside of the day-1 directory and put the data in it. Now it is time to read the input file. To do so we make a function.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}Final result
Now we can replace the test input data and run our script one last time to get the final answer to the puzzle.
1const input = readFile('input.txt');1Callibration sum is: 53386Now we can copy the number we get and paste it in the submit field on the website. Clicking the [Submit] button will give us a resounding congrats, as we did it right!
We are now also able to move forward to the part two of the puzzle.
The final step is to commit our final code.
1git add .
2git commit -m "day 1 part 1 final result"Now allow me to invite you to follow along with the second part. Day 1, part 2