https://adventofcode.com/2021/day/3
Day 3 wants us to calculate the most common bit for each index value in a list of strings. We will then turn that string into binary and do some mathematical operations with it. Ie
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Will turn into 10110 which is 22 in decimal.
To tackle this, I am going to reduce the binary string array into a count of how many 1s for each position. So using the above example, that would reduce down to [7,5,8,7,5]
. Since I also know the length of the array, if the count is larger than length/2
then I know that binary value for that index should be 1. From there I can work out the binary string and finally the decimal value.
Part 2 is a bit trickier. Instead of a single pass through the array, it requires us to recursively reduce the array by:
1) Start from the first position
2) If the array only has one element, this is the value
3) From the existing array, look at the most common bit in the current position
4) Filter the array to only include the elements that have that bit value in that index
5) Go back to 2) with the remaining array and increment the position by one.
This problem is well suited for a recursive function.
Top comments (0)