Website title

Computing: The Details
Lex's blog of curious computer-related shenanigans.

Blog post

Solving Advent of Code 2022 on the Sinclair ZX Spectrum: Part 3

Published: 2023-03-16

This blog post is also available in video form! Watch it on YouTube

Part of a series of posts: < Previous in series

If this doesn't make sense, see part 1

Day 9

See the problem description on adventofcode.com/2022/day/9

The idea for this task was that you're tracking the end of a rope as it swings around. The rope is split into discrete segments, each segment occupies a cell in a square grid, and moves from cell to cell chasing the segment ahead of it. There's a bunch of rules for which cell it moves to. The movement rules are a little odd, and annoying to implement, but not too much of a problem. The challenge is to track the end of the rope as the head of the rope moves around. Initially the rope is only two segments long, but then for the second part of the task it's ten segments long.

The answer that I need to provide for each part is the number of squares that the tail of the rope visited. At first this seems easy, just keep a count of the number of squares visited so far. Each time the tail moves, increment the count. But this only works if the tail never crosses over its own path. So actually I should only count a step if it moves onto a space that's never been used before.

As explained in part 2 of this series, I have been prototyping solutions in python. For day 9, once I had made my initial prototype, I then used it to analyse the size of the problem.

I first checked the size of the grid that the rope moves around in. This isn't specified in the input file. All I know is where the rope starts and how it moves. I calculated the extents of the rope's movement, and I found that the range in X is 234 units, and the range in Y is 286 units. This means that for the Y axis, the range of movement is greater than can fit in a byte. My Y coordinates need to be at least 9 bit numbers, which practically means they should be 16 bit numbers. The X coordinates could fit in one byte if I am careful with where the origin is.

Now consider that I need to track where the tail of the rope has been before, so I know what to count and what not to count. I could do this by keeping a list of all the places that the rope has been to. When I move the rope, I can check if the new tail coordinates are in that list. If they are, I know not to add to the count. Otherwise I will add one to the count.

As the list grows, it becomes more costly to lookup values in this list. The other option is to have a 2D array that is as large as I expect the grid to be, and have each element be a flag to indicate if that cell has been visited. Indexing into this grid will be fast regardless of how long the path gets.

So which of these methods should I use?

Well, first we need to consider how much memory I have available. I have 48k. I lose about 7k to the video memory. I lose about 9k to the input file. I will probably need about 2k for the program code. That leaves me with roughly 30k for any data structures that I need.

So, let's see about keeping a list of all the squares I've visited. For the first part of the task, I visit about 6000 squares. For each one I need to keep the X and Y coordinates. If I use a 16 bit number for each one, that's 4 bytes per square. This means I need about 24k for my list. That will fit in my 30k of free space. As mentioned previously, I could probably get this down to 18k since the range of X values I need will fit in one byte, allowing me to use only 3 bytes per coordinate.

Okay, so that will work, but I suspect it will be very slow. Let's see if the other method will work.

I need a 2D array of flags. I know I need at least 234*286 flags. That's nearly 67 thousand flags. Clearly I can't have a byte for each flag, since that would be about 67k, and I only have 30k. However, a byte could store 8 flags quite easily. If I pack the flags in like this then I only need about 8k for all the flags. This is much more compact than the list method, and has the big advantage that it is less likely to break for larger inputs.

If I was to use a longer input file that visited more spaces, the list gets longer, and the lookup time gets longer with it. Whereas the grid of flags has a constant lookup time. The grid method limits the range of coordinates a little more, but I can future proof it a little by using that spare space I have to make the grid larger in each direction.

If I use a grid that's 336*336 cells in size, that means I use 14k for the grid, and I have comfortable margins around what my input file uses, so hopefully it would work for lots of other input files too.

Something I would love to see in Advent of Code is more detail on the constraints that the file was generated with. I would love to know the exact limits of the generated files, so that I could be more certain about how my program will handle files other than my own.

I have to do quite a bit of arithmetic to set each flag in the grid. Since it's just a huge bitmap, I need to calculate which byte contains the flag I want to set, calculate which bit of that byte is the right flag, set that bit without disturbing any other bits, and then write it back to the bitmap.

Once the rope stops moving, I then iterate over the whole grid and count the number of bits in each byte. I haven't yet experimented with keeping a count as I move through the input file. I'm not sure if it will be faster or not, but I want to find out.

So that was day 9. This one feels kinda tricky because I don't know if my program would work for all possible inputs. It works for my input data, and I've tried to make it support a wide range of values, but I'll never know for sure if it supports them all.

Anyway, it works for me, so I'm calling that one complete and moving on to day 10.

Full listing on GitHub

Day 10

See the problem description on adventofcode.com/2022/day/10

Day 10's task was curious. The first part felt like many of the other tasks that have gone before, but the second part ended with rendering a bitmap image of some text. The text is the answer. To do this you have to simulate a really simple CPU.

The simulation of the CPU is the easy part. For this task I want to talk about the bitmap image rendering part. The ZX Spectrum video RAM is split into two parts, the first contains a bitmap image with one bit per pixel. The second section encodes all the colour data, and a few other attributes. The screen is split into 8x8 pixel squares, and each square can only have two colours. The bitmap selects which of the two colours is visible for each pixel.

If you've played many games on the ZX Spectrum, you've probably seen the effects of this, when a player walks in front of an object on the screen that is normally a different colour, the program must choose only one pair of colours to draw, and so sometimes the player colours leak onto the object that they're close to, or vice versa.

In the case of my solution to this task, I'm happy with the default black text on a beige background, so I needn't change anything in the colour data section of the video RAM. I only need to update the bitmap area. There is one non-obvious thing about the bitmap data though. It's not in the order you might expect.

It would be convenient if the pixels were all in order, left to right, top to bottom. They aren't. They do go from left to right in order, but each time you get to the end of a line, you jump down by 8 pixels and reset to the start of the line. That is, until you get to about one third of the way down the screen, then you jump back up to line 2, and repeat this process until you've visited every pixel in the top third of the screen, then you do the same on the middle third of the screen, and then once more on the last third.

This might seem odd at first, but there is a good technical reason for this order. I'll not get into the details here, but it simplifies some of the video hardware. So now I have to deal with this surprising order of lines in my code. It's not actually too hard to do, since the last three bits of the high byte directly control the Y coordinate within a single square, and the bitmap I need to render fits in a one square high strip.

I did spend a while getting this wrong, and rendered all sorts of garbage to the screen before I finally got all the maths right. I bet this was a frustration shared by most 80s game developers who had to deal with this.

The computation was simple enough though, just requiring some careful thought about how things align when drawing the bitmap.

So that was day 10. Quite a fun one.

Full listing on GitHub

Day 11

See the problem description on adventofcode.com/2022/day/11

I didn't like this particular task. It felt so much more tedious than everything that went before. Certainly the least fun task so far.

If we ignore all the flavour text around the task description for this one, it reduces to just applying simple arithmetic to some numbers over and over again. There was no need for large data structures, the memory footprint is fairly low for this task.

If you just follow the instructions provided, then the numbers you will be dealing with get really big. Way too big to fit in a 32 bit number. They grow exponentially and quickly become too big to handle in a reasonable time. The insight you were supposed to find was that the arithmetic needn't use such big numbers.

The important thing to notice is that you can do all of your addition modulo some fairly small number. Unfortunately, despite making use of this, the largest numbers I had to deal with still got wider than 32 bits, so I had to make a copy of my maths library that could handle 48 bit integers.

Now, the rest of the logic for this task is nothing worth talking about, but something that is worth talking about is the amount of time I spent debugging this one.

There is something that I had failed to take into account. Whenever I tested this program, I got the right answer for the first part, and I got a wrong answer for the second part. What was really strange was that I got a different wrong answer each time even if I hadn't changed anything. So clearly something was very wrong.

I started debugging this and stepped through the computation in the debugger in my emulator. At each step it seemed that the computation was all correct. I stepped through the first few iterations of the algorithm, and they all worked. I jumped a few hundred steps ahead, still correct. Then I jumped a much longer way ahead and found that one of the numbers was wrong.

Hmm. How am I going to find out at which exact point the computation that I am doing in the emulator diverges from the python reference code that worked fine. Well to do this I decided to modify the emulator. I added in some custom code that would save a particular range of memory from the emulator into a file each time it reached a particular instruction that I chose because it wasn't used anywhere else in my program or in the ROM.

I then wrote some more python code to decode this memory dump and compare it to what my python implementation was doing. I found the exact time at which the first error occurred, many minutes into the program run time. Once I knew how far to step into the program, I started the debugger again, stepped to the right place, and … it worked fine.

This was really frustrating. This was by far the most effort I had put into debugging one of these programs. All of the logic in my program was correct. I could see that even if it started with wrong values, it still did the right computation each time. Something else in the system was messing with the values in the middle of the computation.

After hours debugging, I suddenly realised what it was, and the solution was simple.

Most of the binary operations in my maths library use the IY register to point to the second operand. The IY register is also used by the BASIC ROM without saving and restoring it. This would be fine if there was no ROM code running, and you'd think that would be the case while my code is running, but actually it's not.

I was already saving and restoring the IY register value for the purposes of calling into the ROM's print routines, since it expects IY to be untouched. But what I had missed was that the timer interrupt handler uses it too.

The reason this hasn't been a problem before is because none of my programs have ever needed to run for as long as this one does. It takes about 9 hours to complete. The emulator that I use can go several hundred times faster than real time, so it only takes about 90 seconds on my laptop. The fact is that the timer interrupt only uses IY if the timer counter overflows. The counter overflows approximately once every 22 minutes. Naturally that happens many times if you're running your code for 9 hours.

I disabled interrupts, and ran my code again, it worked first time.

None of the other programs had hit this issue, because they all ran in less than 20 minutes. They did still need fixing though, since the timer is always running, and so depending on when the program starts they might hit this same issue.

I spent a long time looking for this bug. It turned out to be a really simple fix.

Full listing on GitHub

Part of a series of posts: < Previous in series