Write a method named dockingMemoryData
that processes a file of memory instruction data and manages storage of values into an address space of simulated memory, using a bitmask to modify values before they are stored.
Your method accepts as its parameter a string representing the name of a file of instruction data.
Values and memory addresses are both 36-bit unsigned integers.
(The entire 36-bit address space begins initialized to the value 0 at every address.)
Each line of the input can either update the bitmask or write a value to memory.
For example, the line of mem[8] = 11
would write the value 11
to memory address 8
.
The bitmask is a string of 36 bits, written with the most significant bit (representing 2^35) on the left and the least significant bit (20, that is, the 1s bit) on the right.
The current bitmask is applied to values immediately before they are written to memory: a 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged.
For example, consider the following program, stored in a file named memory.txt
:
mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0
The first line of the program specifies a bitmask.
The mask it specifies will overwrite two bits in every written value: the 2s bit is overwritten with 0, and the 64s bit is overwritten with 1.
The next instruction asks to write the value 11 to memory address 8.
But we must first apply the bitmask as follows, which changes the value from 11 to 73:
value: 000000000000000000000000000000001011 (decimal 11)
mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
result: 000000000000000000000000000001001001 (decimal 73)
Then, the program tries to write 101 to address 7.
This time, the mask has no effect, as the bits it overwrote were already the values the mask tried to set.
value: 000000000000000000000000000001100101 (decimal 101)
mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
result: 000000000000000000000000000001100101 (decimal 101)
Finally, the program tries to write 0 to address 8.
Because of the bitmask, 64 is written to address 8 instead.
Note that this overwrites the 73 that was written there by a previous line.
value: 000000000000000000000000000000000000 (decimal 0)
mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
result: 000000000000000000000000000001000000 (decimal 64)
Your method should return (as a long
) the sum of all values left in memory after the simulated program completes.
Our previous example ends up with two values modified in memory: a 101 at address 7 and a 64 at address 8.
So the call of dockingMemoryData("memory.txt")
would return 101 + 64 or 165
.
You may assume that the file exists and is readable,
that it follows the format described above,
and that there will be at least one line of input in the file.
(This exercise is based on the Advent of Code 2020, day 14.)