Solving Advent of Code 2022 on the Sinclair ZX Spectrum: Part 2
Published: 2023-01-08
This blog post is also available in video form! Watch it on YouTube
Part of a series of posts: < Previous in series | Next in series >
If this doesn't make sense, see part 1
Day 6
See the problem description on adventofcode.com/2022/day/6
This is gonna be a quick one. The task for day 6 is fairly simple. You need to scan a sliding window across a string, and detect when all the characters in that window form a unique set.
Parts 1 and 2 are the same except for the window size.
There's really nothing interesting in the code for this one, none of it was tricky to do in assembly, so I won't dwell here. Days 7 and 8 are more exciting.
Full listing on GitHub
Day 7
See the problem description on adventofcode.com/2022/day/7
When I first read the details for this challenge, I thought it was going to be a nightmare to implement in assembly. The input file resembles a shell session output, where a user is moving around a file system with cd, and checking the sizes of files in the directories they enter. The files and directories all have names but the full path names are never specified, only implied by the route the user takes through the file system.
I was expecting to build some kind of tree data structure, but at first I thought I was going to have to track file names, which meant dealing with strings of unknown sizes. This is easy to do in a high level language, even C style strings would feel like luxury for this purpose. But actually it turns out I don't need to think about the file names at all.
I looked closely at the description for this task before I started writing my input parsing code. The answers I need are just the sizes of some specific directories. I never actually need to know what the name of any file is. At least, not for the purposes of getting an answer.
But perhaps I do need the file names for parsing the tree? After all, I only know what directory the user is in by its name. Well, actually I discovered that in this fantasy shell session, the user is very predictable. They always descend into directories in order, and descend all the way to the leaves of each directory before continuing on to the next directory.
With this in mind, most of the input file can be ignored, and in fact there's several places in my parsing code where I simply skip over parts of the input.
The first line in the file tells us nothing, as far as I can tell from the examples I have seen, this line is always the same, so I can ignore it. Any line that says "$ ls" can just be ignored. I know that the user always does this after entering a directory. As soon as I see "$ cd <some_dir>", I already know that the next line will be "$ ls", so I can ignore it. Whenever I see a line that starts with a number, I only need to read the number, then I can skip over the rest of the line since the file name doesn't matter at all. The lines that start with "dir" are also safe to ignore entirely. As we've established already: the name doesn't matter, and that's the only real information on those lines.
Most of the input for this task is just thrown away.
Upon discovering all of this, I first wrote some python code that implements the algorithm I need. Having seen the difficulty start to ramp up by now, I had decided that from here on I probably needed to have a working prototype in a high level language before I tried to write any assembly code. Before I show you how I solved day 7, let's take a quick detour into how I prototyped solutions in python and then ported them to assembly.
A side bar about prototyping
python, for me, is an ideal language for Advent of Code. It's easy to write, and the built in data structures and string processing routines make parsing of the input really easy. The problem is that once I have a python solution, I need to translate it into assembly code. For some operations this translation is really obvious. Simple arithmetic is easy, for example. But for other things it's not so obvious. Let me show you.
Let's sum a list of numbers in python.
#!/usr/bin/env python3
inp="""123
234
345
456
567
678
"""
print(sum(map(int,inp.strip().split('\n'))))
The list starts off as text, which needs to be parsed, each line is one number. Here this is done by splitting the input into lines, and then casting each one to an int. I've used the map function to do this, and I've also used the built in sum function. None of this is available to me in assembly code.
Now I'm going to split up these nested function calls.
lines = inp.strip().split('\n')
nums = map(int, lines)
print(sum(nums))
Then I need to get rid of the string split and the int conversion. I don't have a string split function in assembly, and actually I don't need one, I can eliminate the need for it. I'm going to loop over each character in the input. I'm using a while loop here instead of a for loop because they look more like assembly code. I'd like to use goto really, since that's closest to what assembly code looks like, but python doesn't have goto, so I can't. I'm using the name hl for the loop counter, and you'll see why soon.
hl = 0
num = 0
nums = []
while True:
a = ord(inp[hl])
d = a - 48
if d >= 0 and d < 10:
num *= 10
num += d
elif a == ord('\n'):
nums.append(num)
num = 0
else:
break
hl += 1
print(sum(nums))
For each character, I first assume the character is a digit, convert it from ascii into numeric form, then check if it actually is a digit, as I had assumed. If it is, I multiply num by ten and add on the new digit. This is the number parsing algorithm I mentioned in the previous video. If the character is actually a newline, however, I have finished parsing the number, and I can add it to the list.
I then reset the number for the next line. If ever I find a character that's none of these things, then I've finished iterating. I always deliberately make sure there's a null character at the end of my input file, so in python I can emulate this by just adding one to the end of this string.
Now I see another opportunity to optimise this. I don't want to construct a list in assembly code if I can avoid it, and in fact the sum operation doesn't really need to keep a list of all the numbers to sum. Let's just take a running total while I'm parsing the input. I'll also move the loop counter increment statement to the start of the loop, which will make more sense when we look at the assembly code.
hl = -1
num = 0
total = 0
while True:
hl += 1
a = ord(inp[hl])
d = a - 48
if d >= 0 and d < 10:
num *= 10
num += d
elif a == ord('\n'):
total += num
num = 0
else:
break
print(total)
So now I have some python code that really doesn't look like python any more. Normally you'd never write python code like this. It looks awful as python code, but it looks great as a prototype for some assembly code.
Let's look at the assembly that I wrote based on this.
start:
push iy
ld hl, inp-1 l hl points to start of input
loop:
inc hl ; hl += 1
ld a, (hl) ; a = inp[hl]
sub 48
cp 10
jp nc, not_a_digit ; if a >= 0 and a < 10
; num *= 10
ld ix, num
call multen32le
; tmp = a
ld iy, tmp
ld (iy), a
; num += tmp
call add32le
jp loop
not_a_digit:
cp (10 - 48) ; check for newline
jp nz, not_a_newline
; total += num
ld ix, total
ld iy, num
call add32le
; num = 0
ld (iy), 0
ld (iy+1), 0
ld (iy+2), 0
ld (iy+3), 0
jp loop
not_a_newline:
; end of the file
; convert total to string and print it...
You can see why I chose the names hl and a in the python code. These are actually register names on the Z80. This really helps follow what's going on when I translate my python code. It's not a direct translation, as you can see, but it's much easier to go from this python code than it is to go from the initial python code.
The assembly code makes use of my 32 bit add function and string conversion function from the math library that I wrote.
My math library does also have a number parsing function, but I avoided using it here just for demonstration purposes.
So that's how I've been prototyping in python each day. There's a bunch of other things that I do that I won't go into detail for. Things like turning some function variables and arguments into globals, eliminating tuple returns, putting return values in globals, and sometimes even mocking up struct field access. This process made it much easier to get the assembly code right each day. I still had to do lots of debugging, but at least I had a good reference implementation to debug against, and a good starting point for writing my code.
Okay, let's get back to day 7's challenge.
so, I wrote my python code, and I made it look as much like assembly as I could, then I translated the program. For the reasons I explained earlier, there's a bunch of places where it just skips over parts of the input. It skips over the ls lines, the dir lines, and the names of files.
The algorithm builds a tree structure, but you can see that it only stores the links to the other nodes, and a total size for the current node. As mentioned, the names are not important. There's a cursor stack specifically for remembering how to backtrack during parsing. Once the whole tree is parsed, I can recurse the whole tree and add the sizes of child nodes on to parent nodes. Finally, since all the nodes are the same size and stored sequentially, I can then easily iterate over all nodes to compute the answers without having to use recursion.
A little while after getting all of this working, I discovered that I don't actually need to understand the hierarchy of the file system at all. I don't need any of the links between nodes. The only reason I had them was so that I could recurse across the tree structure after I parsed it, but actually I can do the operation that requires recursion during the parsing step. I just add the size of each child node to the parent node whenever I find a "cd .." command. This means I never need recursion for this task at all, only iteration. Perhaps at some point I'll implement this optimisation in my code, but for now it is a missed opportunity.
Day 7 was an interesting challenge with a deceptively noisy input file. So far it's the only challenge where there's been any redundancy in the input file. It took me a really long time to see that despite the fact that the input file represents a tree structure, I never need to recurse across it.
I don't think I would have discovered this if I hadn't been looking so hard for optimisations. For me this is part of the magic of challenging myself to use an assembly language for these tasks. If I had just been using python for this, I wouldn't have bothered looking out for these optimisations.
Full listing on GitHub
Day 8
See the problem description on adventofcode.com/2022/day/8
Okay, on to day 8, last one for this post, and it should be fairly quick.
In this one you have to find particular trees in a grid. Essentially looking for a tall tree with lots of shorter trees around it. I've hugely oversimplified the problem description there, but the interesting part here is another optimisation that I made in the parsing step.
This is an optimisation that is obvious in hindsight, but I probably wouldn't have thought about it if I was using a high level language to solve this problem.
For my solution to this task, there's not really an input parsing step. Well, technically there is one, but it's probably not doing what you think. You might expect me to parse the digits in the file, convert them from ascii values into plain numeric values, maybe even insert them into an array, and then start to process the data. But actually the absolute height of the trees, which is what these numbers represent, is not so important.
The important part is the differences between pairs of trees. I don't need to convert the ascii characters to numbers, because ascii has quite sensibly decided to put all the digits right next to each other in order. If I subtract the ascii value for 4 from the ascii value for 7, then I get the number 3. I needn't bother convert these numbers first, since I would get the same result here anyway.
So, I don't have much set up effort to do before I start computing the result for this task. I need to know how wide the grid is, and how tall it is, so I know how far to iterate, and how to calculate the memory address of each tree digit. But that's all. When it comes to the computation, the raw values from the file are just fine. I don't need to put them into an array or list either. I can just load them directly from where the file is in memory.
As for the rest of the solution to day 8, well I'm sure you can imagine it, it's just iterating over a grid in various ways, and performing simple arithmetic as you do so.
Full listing on GitHub
Part of a series of posts: < Previous in series | Next in series >