#adventofcode Day 2 and 3 — C and Python

Hello!

Since day 2 was pretty easy to solve I actually included day 3 here too. The day 2 challenge was to traverse a matrix, get the highest and lowest number from every line, calculate the difference and add it to a sum.

For example, given the following spreadsheet:

5 1 9 5
7 5 3
2 4 6 8
  • The first row’s largest and smallest values are 9 and 1, and their difference is 8.
  • The second row’s largest and smallest values are 7 and 3, and their difference is 4.
  • The third row’s difference is 6.

Nothing fancy. I did it in C in 20 minutes max, just because I forgot how to read from a file (long time no C haha).

Day 3 challenge is quite awesome and took me 2 hours to actually solve it.

Given a number, represented in an infinite 2D matrix, calculate the Manhattan distance between the location of the number and the square in the center of the matrix (in our case 1). Representation of the 2D infinite matrix:

17  16  15  14  13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23---> ...

This is an Ulam Spiral. For the sake of the example let’s suppose you were given the number 21. The Manhattan distance for this number is 4 . Steps to reach the square 1 are: right right up up . 4 moves hence the distance is 4. My input was: 265149 . Imagine creating the spiral for this number.

So, the algorithm:

After intense reading I saw that every right corner of spiral is an odd square. 9, 25, 49, etc … So what if I square root my number and find the nearest odd square root? That means I will have the right corner of my spiral. If you check the example above, you’ll see that the distance from every right corner of the spiral is the square root of the number — 1 . From 9 the distance is 2. Check it out. From 25 the distance is 4 and so on.

Therefore, if I have the nearest odd square root I can count the distance to my number and add it to the initial one. We reduced this complex problem to a very basic one.

Coding time (I removed some steps because I really don’t wanna ruin it since day 3 is not finished yet. The example works only if the input number is in the right side of the center of the line):

Second part it was easy with some research here and there ;). Good luck!

Liked this post?

If you enjoyed this article, please help out with a clap or a share.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.