logo CodeStepByStep logo


Write a method named DockingMemoryData2 (similar to the previous exercise, dockingMemoryData) that applies its masks to indexes rather than values. As in the previous exercise, your method accepts as its parameter a string representing the name of a file of instruction data. This time, when you see an instruction to write a value to memory, apply the mask to the index provided (not the value) by evaluating each bit of the index and bitmask as follows:

  • If the bitmask bit is 0, the corresponding memory address bit is unchanged.
  • If the bitmask bit is 1, the corresponding memory address bit is overwritten with 1.
  • If the bitmask bit is X, the corresponding memory address bit is floating, meaning that it represents both 0 and 1.

For example, consider the following program, stored in a file named memory.txt:

mask = 000000000000000000000000000000X1001X
mem[42] = 100
mask = 00000000000000000000000000000000X0XX
mem[26] = 1

When this program executes the command mem[42] = 100, it first applies the bitmask to the index 42:

address: 000000000000000000000000000000101010  (decimal 42)
mask:    000000000000000000000000000000X1001X
result:  000000000000000000000000000000X1101X

After applying the mask, four bits are overwritten. Floating bits (X) take on every possible combination of values; with two floating bits, four actual memory addresses are written:

000000000000000000000000000000011010  (decimal 26)
000000000000000000000000000000011011  (decimal 27)
000000000000000000000000000000111010  (decimal 58)
000000000000000000000000000000111011  (decimal 59)

Next, the program is about to write to memory address 26 with a different bitmask:

address: 000000000000000000000000000000011010  (decimal 26)
mask:    00000000000000000000000000000000X0XX
result:  00000000000000000000000000000001X0XX

This results in an address with three floating bits, causing writes to eight memory addresses:

000000000000000000000000000000010000  (decimal 16)
000000000000000000000000000000010001  (decimal 17)
000000000000000000000000000000010010  (decimal 18)
000000000000000000000000000000010011  (decimal 19)
000000000000000000000000000000011000  (decimal 24)
000000000000000000000000000000011001  (decimal 25)
000000000000000000000000000000011010  (decimal 26)
000000000000000000000000000000011011  (decimal 27)

As with the previous exercise, your method should return the sum of all values left in memory after the simulated program completes. In our example, the call of DockingMemoryData2("memory.txt") would return 208.

(This exercise is based on the Advent of Code 2020, day 14.)

Method: Write a C# method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.