
Day 1, part 2
Day 1 challenge of the mighty Advent of Code 2024
Introduction
If you haven't already, please first take a look at Day 1, part 1 as this article is a continuation of the Advent of Code day 1 puzzle. This part of the challenge is available only when you successfully finished the part 1. The second part of the challenge is described under -- Part Two -- section here.
What is the new problem?
Now we are asked to look at the test data again.
1two1nine
2eightwothree
3abcone2threexyz
4xtwone3four
54nineeightseven2
6zoneight234
77pqrstsixteenBefore we were looking for the first and last digit, taking into consideration only numeric characters (characters from 0 to 9), but the strings of text we are given are built also with numbers written as a words (zero, one, two etc.).
Lets take a look at the word two1nine. If we feed our algorithm from part 1, we will get 11 as a result (reading from the beginning and from the end results in finding 1 both times), which in turn is the calibration value for this string as we only have one string so the final sum is built out of this one calibration value.
But with the new information, the correct calibration value is 29 as we first replace the words with digits getting 219 and then we proceed with the steps we already know.
Solution
To be able to read the word written digits, we first have to find them and then replace them with the corresponding digit. We have to do it looking from the beginning of the given string as well as looking from the end. Also, as we know that we later look only for the first and last digit in the string, when replacing the words with numbers, we have to only replace the first word we met and the last word we met.
Lets start, again, by defining the variable for input data and set it to the test data for which we know the results and in general the amount of data is so small that we can easily keep track of it.
1two1nine
2eightwothree
3abcone2threexyz
4xtwone3four
54nineeightseven2
6zoneight234
77pqrstsixteenLet's figure out what the strings will look like if we replace the first and last spelled number with a digit:
1219
28wo3
3abc123xyz
4x2ne34
549eight72
6z1ight234
77pqrst6teenFind first number word in the string
Now, how can we find out the first spelled number in a string?
We can use string method search to look for a word occurrence in the string. This method returns the index at which the word starts and -1 if it hasn't found the word. We can do this operation for all the words from zero to nine, find the one with the lowest index and replace that word, leaving all the rest as is.
1const testInput = `two1nine
2eightwothree
3abcone2threexyz
4xtwone3four
54nineeightseven2
6zoneight234
77pqrstsixteen`;
8const lines = textToLinesArray(testInput);
9const spelledNumbers = [
10 'zero',
11 'one',
12 'two',
13 'three',
14 'four',
15 'five',
16 'six',
17 'seven',
18 'eight',
19 'nine',
20];
21function replaceFirstSpelledNumber(string) {
22 const wordIndexes = getSpelledNumberIndexes(string);
23 console.log(wordIndexes);
24}
25function getSpelledNumberIndexes(string) {
26 return spelledNumbers.map((word) => string.search(word));
27}
28replaceFirstSpelledNumber(lines[0]);this piece of code returns array with indexes for each spelled number which looks like this:
1[
2 -1, -1, 0, -1, -1,
3 -1, -1, -1, -1, 4
4]Analyzing the results we can see that if found words with indexes 2 and 9 at positions 0 and 4 respectively. These of course are the words two and nine. We store the spelled digits in an array like this for a simple reason: the index of each word corresponds to it digit what might be useful later.
But now, how can we find the index of the word which appeared first?
We can find the smallest number in the array using Math.min, but because of the -1 values in the array, the answer is going to be wrong, so before we use the Math.min lets first filter out all the -1s. New version of our replaceFirstSpelledNumber function looks now like this:
1function replaceFirstSpelledNumber(string) {
2 const wordIndexes = getSpelledNumberIndexes(string);
3 const foundWords = wordIndexes.filter((index) => index >= 0);
4 const firtsWordPosition = Math.min(...foundWords);
5 const firstWordIndex = wordIndexes.indexOf(firtsWordPosition);
6 console.log(
7 `First found word is ${spelledNumbers[firstWordIndex]}. It is starting in the given string at position ${firtsWordPosition}`
8 );
9}and it gives us following information:
1First found word is two (2). It is starting in the given string at position 0Thanks to that information we know what digit is first both spelled and as a number and where it starts in the given string.
Replace word with a digit
The data we were able to gather so far is enough for us to be able to replace the written digit with the number. Here is the code after few modifications.
1function replaceFirstSpelledNumber(string) {
2 const wordIndexes = getSpelledNumberIndexes(string);
3 const foundWords = wordIndexes.filter((index) => index >= 0);
4 const firtsWordPosition = Math.min(...foundWords);
5 const firstWordIndex = wordIndexes.indexOf(firtsWordPosition);
6 const updatedString = replaceInString(
7 string,
8 firtsWordPosition,
9 spelledNumbers[firstWordIndex].length,
10 firstWordIndex
11 );
12 console.log('New string after replacing: ', updatedString);
13}
14function getSpelledNumberIndexes(string) {
15 return spelledNumbers.map((word) => string.search(word));
16}
17function replaceInString(string, startPosition, length, replacement) {
18 const chars = string.split('');
19 chars.splice(startPosition, length, replacement);
20 return chars.join('');
21}Now we introduced the general purpose function replaceInString which can take an input string, start position, the amount of characters we want to replace and the replacement string, which in our case is just the digit as a number. Running this code gives us:
1New string after replacing: 21nineFind and replace the last word
So far so good, we successfully found and replaced the first spelled number with the corresponding digit. We can try to do the same for the last one by analogy.
1function replaceLastSpelledNumber(string) {
2 const wordIndexes = getSpelledNumberIndexes(string);
3 const foundWords = wordIndexes.filter((index) => index >= 0);
4 const lastWordPosition = Math.max(...foundWords);
5 const lastWordIndex = wordIndexes.indexOf(lastWordPosition);
6 return replaceInString(
7 string,
8 lastWordPosition,
9 spelledNumbers[lastWordIndex].length,
10 lastWordIndex
11 );
12}
13const stringWithReplacedFirstWord = replaceFirstSpelledNumber(lines[0]);
14console.log(replaceLastSpelledNumber(stringWithReplacedFirstWord));and thanks to that we get the expected result which is 219. Lets now do it for all the test values and see the results. I will also use the expected values we did figured out manually to see if the results we get are the results we expect.
1lines.forEach((line) => {
2 const stringWithReplacedFirstWord = replaceFirstSpelledNumber(line);
3 console.log(replaceLastSpelledNumber(stringWithReplacedFirstWord));
4});This unfortunately throws an error after few successful lines:
1219
28wo3
3abc123xyz
4x2ne34
549eight72
6/home/michal/Projects/advent-of-code-2023/day-1/main.js:110
7 spelledNumbers[lastWordIndex].length,
8 ^
9TypeError: Cannot read properties of undefined (reading 'length')What happened here is us being silly and assuming that we always have two words to replace, where we shouldn't expect any word to be present. Lets add some checks to our first and last words replacing functions. Let's see that on the replaceFirstSpelledNumber exapmle.
1function replaceFirstSpelledNumber(string) {
2 const wordIndexes = getSpelledNumberIndexes(string);
3 const foundWords = wordIndexes.filter((index) => index >= 0);
4 if (foundWords.length === 0) {
5 return string;
6 }
7 const firtsWordPosition = Math.min(...foundWords);
8 const firstWordIndex = wordIndexes.indexOf(firtsWordPosition);
9 return replaceInString(
10 string,
11 firtsWordPosition,
12 spelledNumbers[firstWordIndex].length,
13 firstWordIndex
14 );
15}Here we have added the if statement which checks if we found any words in the string and if not we simply return the string as is, without any further calculations (see short circuiting). Lets try one more time to run the code on the whole test data.
1lines.forEach((line, idx) => {
2 const stringWithReplacedFirstWord = replaceFirstSpelledNumber(line);
3 const result = replaceLastSpelledNumber(stringWithReplacedFirstWord);
4 console.log(`${result} -> ${expectedOutput[idx]} (${expectedOutput[idx] === result})`);
5});1219 -> 219 (true)
28wo3 -> 8wo3 (true)
3abc123xyz -> abc123xyz (true)
4x2ne34 -> x2ne34 (true)
549eight72 -> 49eight72 (true)
6z1ight234 -> z1ight234 (true)
77pqrst6teen -> 7pqrst6teen (true)It looks that our effort paid off, lets now try feed our main algorithm with data processed by what we have now. But first would be good to commit the changes.
1git add .
2git commit -m "build alghorithm to replace spelled numbers to digits"Using our word replacer in the main program
First lets build the function that performs the replacing functionalities for a given string and returns the result.
1function replaceFisrtAndLastWordWithADigit(string) {
2 const stringWithReplacedFirstWord = replaceFirstSpelledNumber(string);
3 return replaceLastSpelledNumber(stringWithReplacedFirstWord);
4}This function is build based on the testing code we wrote above. It just returns the built string instead of logging it. And in the main function we will update the code to utilize this new function.
1function getCalibrationValues(text) {
2 const lines = textToLinesArray(text);
3 const substitutedLines = lines.map(replaceFisrtAndLastWordWithADigit);
4 const calibrationValues = substitutedLines.map(getCalibrationValueFromString);
5 return sumNumberArray(calibrationValues);
6}And after running the script with the test data passed to getCalibrationValues we get:
1Callibration sum is: 281And this is the correct value. So we can now do a bit of cleaning up and commit the changes, before we run the whole thing on the real input data.
The final code looks like this:
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5// const input = readFile("input.txt");
6const input = `two1nine
7eightwothree
8abcone2threexyz
9xtwone3four
104nineeightseven2
11zoneight234
127pqrstsixteen`;
13const spelledNumbers = [
14 'zero',
15 'one',
16 'two',
17 'three',
18 'four',
19 'five',
20 'six',
21 'seven',
22 'eight',
23 'nine',
24];
25function getCalibrationValues(text) {
26 const lines = textToLinesArray(text);
27 const substitutedLines = lines.map(replaceFisrtAndLastWordWithADigit);
28 const calibrationValues = substitutedLines.map(getCalibrationValueFromString);
29 return sumNumberArray(calibrationValues);
30}
31function textToLinesArray(text) {
32 return text.split('\
33');
34}
35function replaceFisrtAndLastWordWithADigit(string) {
36 const stringWithReplacedFirstWord = replaceFirstSpelledNumber(string);
37 return replaceLastSpelledNumber(stringWithReplacedFirstWord);
38}
39function replaceFirstSpelledNumber(string) {
40 const wordIndexes = getSpelledNumberIndexes(string);
41 const foundWords = wordIndexes.filter((index) => index >= 0);
42 if (foundWords.length === 0) {
43 return string;
44 }
45 const firtsWordPosition = Math.min(...foundWords);
46 const firstWordIndex = wordIndexes.indexOf(firtsWordPosition);
47 return replaceInString(
48 string,
49 firtsWordPosition,
50 spelledNumbers[firstWordIndex].length,
51 firstWordIndex
52 );
53}
54function replaceLastSpelledNumber(string) {
55 const wordIndexes = getSpelledNumberIndexes(string);
56 const foundWords = wordIndexes.filter((index) => index >= 0);
57 if (foundWords.length === 0) {
58 return string;
59 }
60 const lastWordPosition = Math.max(...foundWords);
61 const lastWordIndex = wordIndexes.indexOf(lastWordPosition);
62 return replaceInString(
63 string,
64 lastWordPosition,
65 spelledNumbers[lastWordIndex].length,
66 lastWordIndex
67 );
68}
69function getSpelledNumberIndexes(string) {
70 return spelledNumbers.map((word) => string.search(word));
71}
72function replaceInString(string, startPosition, length, replacement) {
73 const chars = string.split('');
74 chars.splice(startPosition, length, replacement);
75 return chars.join('');
76}
77function getCalibrationValueFromString(string) {
78 const firstDigit = getFirstDigitInString(string);
79 const lastDigit = getLastDigitInString(string);
80 return firstDigit * 10 + lastDigit;
81}
82function getFirstDigitInString(string) {
83 const chars = string.split('');
84 for (let i = 0; i < chars.length; i++) {
85 const char = chars[i];
86 if (isCharADigit(char)) {
87 return parseInt(char);
88 }
89 }
90 throw new Error('No digits found');
91}
92function getLastDigitInString(string) {
93 const chars = string.split('');
94 for (let i = chars.length - 1; i >= 0; i--) {
95 const char = chars[i];
96 if (isCharADigit(char)) {
97 return parseInt(char);
98 }
99 }
100 throw new Error('No digits found');
101}
102function isCharADigit(char) {
103 return !isNaN(parseInt(char));
104}
105function sumNumberArray(numbers) {
106 return numbers.reduce((acc, curr) => acc + curr, 0);
107}
108console.log('Callibration sum is: ', getCalibrationValues(input));1git add .
2git commit -m "use word replacing in main function"Real input data
If you looked at the provided code carefully, to run this whole thing with the real data we simply have to uncomment the input file reading and delete the test data. The result we get is 53293. Submitting this result unfortunately is wrong. Now lets think of why is that.
The intersecting words problem
So the problem we encounter is the following: With our word replacing algorithm, every word like sevenine which in turn has digit 7 and 9 will in our code result in 7ine as we do the second replacing operation on the string we get after the first word replacing. Lets analyze how can we overcome this obstacle. First question we can ask is if we really need to replace the whole words by the corresponding digits? Should we at all do the replacement at the first place?
The solution
What if instead of searching for words and replacing them in the strings, and then searching for first and last digits in these strings, omitting all the other characters, we could first prepare the new dataset by extracting just the numbers written in digits and numbers written in words replaced by the digits? Lets have a look at the following function:
1function extractNumbers(string) {
2 let result = '';
3 for (let i = 0; i < string.length; i++) {
4 const substring = string.slice(i);
5 if (isCharADigit(substring[0])) {
6 result += substring[0];
7 } else {
8 const wordIndexes = getSpelledNumberIndexes(substring);
9 const indexOfStartingWord = wordIndexes.indexOf(0);
10 if (indexOfStartingWord >= 0) {
11 result += indexOfStartingWord;
12 }
13 }
14 }
15 return result;
16}This function is building the new output string which will be build out of digit characters only. It goes in the loop from the starting index of the string and each time creates a sub-string starting at the current index till the end of the string. If the first digit of this sub-string is a digit then it appends it to the result. If its not a digit then it finds where each spelled number occurs in the sub-string. Now, if any of the indexes is 0, it means that our sub-string starts with a number-word. In that case we append the corresponding digit to the result, otherwise we do nothing. Checking only for the starting word of each sub-string assures that even words that are overlapping will be catched in the next loop iteration. For example string 1oneightwonexyz0 will be translated to 118210. Now thanks to that our first and last digit searching algorithm can be simplified to just taking the first and the last character of that string. Take a look at the code after all the changes.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');
6const spelledNumbers = [
7 'zero',
8 'one',
9 'two',
10 'three',
11 'four',
12 'five',
13 'six',
14 'seven',
15 'eight',
16 'nine',
17];
18function getCalibrationValues(text) {
19 const lines = textToLinesArray(text);
20 const extractedNumberStrings = lines.map(extractNumbers);
21 const calibrationValues = extractedNumberStrings.map(getCalibrationValueFromString);
22 return sumNumberArray(calibrationValues);
23}
24function textToLinesArray(text) {
25 return text.split('\
26');
27}
28function extractNumbers(string) {
29 let result = '';
30 for (let i = 0; i < string.length; i++) {
31 const substring = string.slice(i);
32 if (isCharADigit(substring[0])) {
33 result += substring[0];
34 } else {
35 const wordIndexes = getSpelledNumberIndexes(substring);
36 const indexOfStartingWord = wordIndexes.indexOf(0);
37 if (indexOfStartingWord >= 0) {
38 result += indexOfStartingWord;
39 }
40 }
41 }
42 return result;
43}
44function isCharADigit(char) {
45 return !isNaN(parseInt(char));
46}
47function getSpelledNumberIndexes(string) {
48 return spelledNumbers.map((word) => string.search(word));
49}
50function getCalibrationValueFromString(string) {
51 const chars = string.split('');
52 const firstDigit = parseInt(chars[0]);
53 const lastDigit = parseInt(chars[chars.length - 1]);
54 return firstDigit * 10 + lastDigit;
55}
56function sumNumberArray(numbers) {
57 return numbers.reduce((acc, curr) => acc + curr, 0);
58}
59console.log('Callibration sum is: ', getCalibrationValues(input));Final result
Running this code now gives us:
1Callibration sum is: 53312And after submitting this answer we are getting the following window.
The final step is to commit our final code.
1git add .
2git commit -m "day 1 part 2 final result"Conclusion
When I was writing this post, I was doing so alongside with solving the puzzle to show you how does the process looks like. I could have first figured out the whole thing and afterwards describe only the final working solution but that's not how it works in real life. I wanted to show you all that the normal thing of solving problems is to make mistakes and try different solutions to get the expected results. So the next time when you find yourself struggling with a problem, remember - we all do and even the most experienced developer makes mistakes. The true key to being better is to try. I hope you all enjoyed this challenge as much as I did and see you in Day 2, part 1