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 1

Published: 2023-01-03

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

Part of a series of posts: Next in series >

Advent of Code is a programming challenge and competition that runs during the 25 days of Advent.

I decided that this year that my challenge to myself for Advent of Code would be to solve each day's challenge with a Sinclair ZX Spectrum program.

The Sinclair ZX Spectrum was a popular British home computer from the early 1980s. It has 48k of RAM. That's not much by today's standards.

I happen to have one in working order, and wanted an excuse to use it more. So I thought this would be a fun way to do that.

Can I do all 25 days on the ZX Spectrum? (Spoiler alert! ... I stopped before I reached the end)

Introduction

Okay, first of all let's see what I'm in for.

Each day of AoC comes in two parts. That's a total of 50 challenges. For each challenge you get a description of the challenge, an input file that you need to process to complete the challenge, and finally a place to submit your answer to see if you got it right.

If you're aiming to get on the leaderboard then you have to be awake at the right time and code as fast as you can. Only the first 100 correct answers score points each day. That's 5AM for me here in England. I'm not aiming for leaderboard positions this year, I'm just having fun with retro computing. So I'm gonna wake up whenever I like.

Each day has two challenges, and normally they're very closely related. Often the first one sets you up nicely for the second one, but sometimes it doesn't. As the days go on, you have to be more clever with how you solve the problems. There's often an obvious solution that's way too computationally expensive to get a result in a reasonable time, and then a more creative solution that's quite fast.

So in summary, what we need to do each day is: parse the input file, process the parsed data to get the answer to part 1, process the input again but this time calculate the answer to part 2.

Of course we only know part 2 after doing part 1. Sometimes you can calculate both answers with one pass over the input data, but at least at first that's not helpful.

I have quite a lot of programming experience, so to make this fun I need to make it harder. So now let's look at how I've made this hard for myself.

The target (The ZX Spectrum)

I've made things hard for myself by choosing a difficult platform to write programs for.

The Sinclair ZX Spectrum from 1982 has only 48kb of RAM. It has a clock speed of about 3.5MHz. You're probably watching this video on a device with a clock that's almost 1000 times faster than this.

Okay, so it's slow, and it hasn't got much RAM. Doesn't this just mean it will take longer? Well, it will take longer, for sure. But there's other problems too. How do I write programs for this machine?

If you start up the machine then all you get is a BASIC interpreter. I mean BASIC as in the language. But it is also basic in that it's not a feature rich development environment that you might expect to use on a modern PC.

I could write BASIC programs for this machine, but BASIC is slow, has some annoying constraints, and also lacks certain operations that I'd have to reimplement with my own functions, which would be much slower than machine code versions. So that's the decision essentially made for me. If I want the performance I need for some of the more intense AoC challenges, then I need to produce machine code.

I've never found a compiler for any language that I'm happy with for the Z80, which is the CPU inside the ZX Spectrum. So instead I decided to make things extra hard for myself and write all of my solution code in Z80 Assembly language. This means all the algorithms and data structures I need, I will need to implement them myself.

RAM is also a problem. I have only 48k. About 7k of that is used by the graphics system. Using this for computation would put garbage on the screen, so I'd like to avoid it if possible. I need to use some of the screen space for outputting the answers anyway. So I'm already down to a practical limit of 41k.

Before I started this adventure I had a look at the size of the input files from the previous year, and I found that most of them are less than 10k about five of them were larger than this, the largest being 20k on day 22.

The input text is unique to each player, and is generated by the server for you. Your answer is different to everyone else's, but I'm not sure how much the input size varies. It might be possible that there's a slight difference in size between players, I'm not sure.

Anyway, I started with the assumption that 20k will be the upper bound. I'm sure that'll be enough, right? (in the biz, this is known as foreshadowing)

So that leaves me with 21k of space for my program. I thought that sounded like a lot at first. But then I remembered that I also need any working data structures to fit in the remaining space. Turns out most programs fit into 2k including space for small variables, so that leaves 19k for any data structures I need. Still, that should be plenty of space, right? (in the biz, this is known as foreshadowing repeating a joke)

Time for your spoiler warning. From here on expect some mild spoilers for the AoC challenges.

The plan

I'm going to cover days one to five in this post, and then later days will be in future posts. I won't be going into much detail for some of the easier challenges, but I will go into lots of detail for the more interesting ones that required a little bit of creativity. You've probably already seen other people describing their algorithms in detail if you're into this kind of thing, so I'll try to focus on the challenges that are unique to using a ZX Spectrum for these kinds of programs.

Days one to five were all fairly simple. We'll start at the beginning, with day one, and the first challenge that I have to overcome.

Day 1

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

At the heart of the ZX Spectrum is the Zilog Z80 CPU. People often call this an 8-bit microprocessor. A pet peeve of mine is how people use phrases like these and don't qualify them. If someone says "This is an 8 bit processor", what do they actually mean? Do they mean that the address bus is 8 bits wide? Do they mean that the widest part of the data path is 8 bits? Do they mean that the general purpose registers are 8 bits wide?

So let's clarify this statement for the Z80. It has a 16 bit address bus and an 8 bit data bus, it has registers that are either 8 bits wide or 16 bits wide depending on the operation. The widest adders in the machine are 16 bits wide. So is this an 8 bit micro? Or a 16 bit micro?

Either way, the largest adder I have access to is a 16 bit adder. But actually the more convenient ones to use are the 8 bit adders. So this means the largest integer that I can use with the built in hardware is 2 to the power of 16 minus one. That's 65,535. So here's problem one: this is not big enough for AoC. Regular AoC players will know that the numbers often get big.

It's common for lots of modern machines to have at least 32 bit adders and 32 bit registers. This lets you get numbers up to almost 4.3 billion. This should be plenty for this task. I had hoped that it would be big enough for all of the tasks. (in the biz, this is known as foreshadowing murdering a joke)

So, my first task was to implement 32 bit addition, and also parsing of base 10 numbers. Let's start with adding: there's a pair of registers on the Z80 that make this really easy to do. the IX and IY registers can point to the starting position in RAM of each of the two numbers to add, and then I can load the right bytes from each one using the load instructions that use offsets from the IX and IY registers. Below is the function I wrote for this. It works because you can do a 32 bit add by doing four 8 bit adds, as long as you remember to pass the carry output bit from each add operation to the next higher order add operation.

add32le: ; (ix) = (ix) + (iy)
    push af
    or a
    ld a,(ix)
    adc a,(iy)
    ld (ix), a
    ld a, (ix+1)
    adc a,(iy+1)
    ld (ix+1), a
    ld a, (ix+2)
    adc a,(iy+2)
    ld (ix+2), a
    ld a, (ix+3)
    adc a,(iy+3)
    ld (ix+3), a
    pop af
    ret

Okay, now for number parsing. That means I need multiplication. The algorithm I used for parsing decimal was to parse the first digit, add it to an accumulator, and then for each additional character I find, I multiply the accumulator by 10 and then add on the digit I just found until I run out of digits.

My multiplier implementation is fairly simple, it iterates over the bits of one number, multiplying by two or adding the current value each time. This is a fairly common approach and it works well for this size of number. The problem is that when I parse a number from the input file, I need to do this multiply step once for each digit in the number. There's about 2000 numbers in the file for day 1, usually about 4 digits each. That's 8000 multiplications I need to do. My multiplier isn't unreasonably slow, but it's certainly on the critical path for parsing decimal numbers for day 1.

mul32le: ; (ix) = (ix) * (iy)
    push bc
    push de
    push hl
    push iy
    ; Copy (ix) to (tmp2)
    ld bc, 4
    push ix
    pop hl
    ld de, mul32le_tmp2
    ldir
    ; Copy (iy) to (tmp1)
    ld bc, 4
    push iy
    pop hl
    ld de, mul32le_tmp1
    ldir
    ; set (ix) to 0
    ld (ix+0), 0
    ld (ix+1), 0
    ld (ix+2), 0
    ld (ix+3), 0
    ; 32 step multiply loop
    ld b, 32
    ;ld iy, mul32le_tmp2
    ld de, 4
mul32le_loop:
    ld iy, mul32le_tmp1 ; 20
    call sra32le_iy
    ld iy, mul32le_tmp2 ; 20
    call c, add32le
    call dbl32le_iy
    djnz mul32le_loop
    pop iy
    pop hl
    pop de
    pop bc
    ret
mul32le_tmp1:
    db 0,0,0,0
mul32le_tmp2:
    db 0,0,0,0

Since I know that I only need to multiply by 10 while I'm parsing a number, I can actually create an optimised multiply function that's specifically for multiplying by ten. How does it work?

Well let's start with multiplying by two, multiplying a number by two in binary is really easy. You know from primary school maths that if you need to multiply a decimal number by 10 then you just shift everything over by one digit and put a zero in the units place. Well, as we move from base 10 to base 2, that same shift operation turns from times-ten into times-two. Most CPUs have shift instructions, and the Z80 is no exception. I can multiply by 2 really fast. In fact it's a part of the algorithm for arbitrary multiplication already. But 2 is not 10. So how do I use this information to make multiplying by 10 really fast?

Well, add is quite fast, so if I can build my times-ten just using shifts and adds then I can make times ten be really fast. Let's take X, shift it once to get 2X, we'll keep that for later. Now let's shift 2X again, twice more, to get 8X. Now I can add 2X and 8X together to get 10X.

; Optimised multiply by 10
; (ix) = (ix) * 10
; decomposes 10 into sum of powers of two
; x * 10 === (x * 2) + (x * 8) === dbl(x) + dbl(dbl(dbl(x)))
; three doubles plus an add
multen32le:
    push bc
    push de
    push hl
    push iy
    ; (ix) = (ix) * 2
    call dbl32le
    ; (tmp1) = (ix)
    ld bc, 4
    push ix
    pop hl
    ld de, multen32le_tmp1
    ldir
    ; (ix) = (ix) * 2
    call dbl32le
    ; (ix) = (ix) * 2
    call dbl32le
    ; (ix) = (ix) + (tmp1)
    ld iy, multen32le_tmp1
    call add32le
    pop iy
    pop hl
    pop de
    pop bc
    ret
multen32le_tmp1:
    db 0,0,0,0

My arbitrary multiply function does 64 one-bit shifts and 32 additions. My newly optimised X10 function does 3 one-bit shifts, and 1 addition. That's a huge improvement.

With number parsing going fast, and 32 bit addition working, day 1 becomes easy. I'll spare you the details, it's just adding some numbers together and deciding which one is biggest.

Full listing on GitHub

Day 2

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

Since I had all the infrastructure I had implemented for day 1, it was really easy to get day 2 done.

Day 2 was slightly more complicated than day 1, but not much. The challenge involved evaluating total scores from games of Rock Paper Scissors according to some scoring formula. There wasn't anything in day 2 that was particularly difficult. The only new technique I used here was pre-computing a look up table of values for the scores. I used two different tables to look up the scores given by the outcome of each game. The scoring was different in each part of the challenge, hence I needed a different look up table for each one.

Nothing new enough or exciting enough to discus for day 2.

Full listing on GitHub

Day 3

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

Day 3, still quite early on. The difficulty has not ramped up yet. This is a fairly simple task, but it's an opportunity to talk about parsing, and how I'm actually getting the input files on to the ZX Spectrum.

Well, first of all, when I'm coding I'm actually using an emulator. I have been verifying that my code runs on real hardware too, but during development it's much nicer to have an emulator with a debugger.

Programs are normally loaded on to the ZX Spectrum via a compact cassette, although you can actually use anything that produces a suitable signal. I have used my laptop headphone output to load programs during testing without needing a cassette. I have been using cassettes occasionally too though, for fun.

My build process for my code includes a step where the program and the input file are each turned into the format that the ZX Spectrum can load. These files can be loaded directly by an emulator, or can be converted into .wav audio files. I've been using the .wav method to test on real hardware and to record onto cassettes.

These files need to know where in memory they will be loaded. A third file, which is a small BASIC program, is the first file to be loaded. It runs automatically and loads the other files in the right places automatically. It loads the main program, which starts at address 0x8000, and then the input text, which is loaded at 0xA000. This gives me plenty of space for each of these. I have about 24k of space starting at 0xA000, so that should be plenty of space for even the largest of the input files that I'm anticipating (foreshadowing). The program has an 8k block to use. If the program ever gets bigger than this then it will start to overlap with the input text.

The program knows that the input will start at 0xA000, so to read the input text, it just starts reading from that part of the memory. On modern systems you often find that a program will open a file, and only load a part of it into memory at once, often it doesn't need to store the whole thing in memory, it can stream it from the storage medium as it processes it, and discard the parts it has already processed. On the ZX Spectrum this is not an option. You have to load the whole file, or none of the file. If I wanted to process this in parts, I will have to split it into multiple different files and load one at a time.

Here's an example of a parsing function. If BC points to the start of a line in the file, then running this code puts the length of the line in register E. Of course, it produces incorrect results for lines longer than 255 characters. It also fails for lines of length 0, in which case is returns the length of the next line in the file plus one. These limitations are known, and are not problematic for the given puzzle input.

length_loop:
    ; get the length of this line
    inc bc
    inc e
    ld a, (bc)
    cp 10 ;check for line feed
    jp nz, length_loop
    ; e is now the line length

Another issue is that the user experience is very different for files on tapes. The user has to locate the file on the tape, or sit and wait for the tape to play all the way to the file that the program wants. The ZX Spectrum can't control the tape player. Imagine if you had to manually control the start location of the read head on your hard disk to load a file.

My solution for day 3 is often jumping around the file while parsing it. Since it sometimes needs to scan across several lines at the same time. Having the whole thing in memory is actually really convenient for this purpose. In part 2 there's a need to scan three lines at the same time. This function finds the starts of the next three lines in the file:

find_lines:
    ; upon arriving at find_lines, hl should point to the first char in the first line
    ld (line1_start), hl
find_line_2:
    inc hl
    ld a, (hl)
    cp 0
    jp z, part2_done
    cp 10 ; check for newline
    jp nz, find_line_2
    inc hl
    ld (line2_start), hl
find_line_3:
    inc hl
    ld a, (hl)
    cp 10 ; check for newline
    jp nz, find_line_3
    inc hl
    ld (line3_start), hl
found_lines:
    ; we now have three pointers, one pointing to each line in this group

Anyway, the rest of the details for part 3 are not particularly interesting. Let's move on.

Full listing on GitHub

Day 4

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

Day 4 also wasn't particularly interesting. It was just basic arithmetic over and over again. It didn't take me long to implement a solution using things I'd already experienced in the first few days.

Full listing on GitHub

Day 5

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

Day 5 was interesting because it was the first one that required me to implement a data structure that I hadn't given much thought to before.

In modern high level languages you get lots of things easy. Suppose you need a LIFO queue, (Last In, First Out) you can just summon one from the eather with a single line of code. I'm writing Z80 assembly, I have to bring all my own data structures.

The disadvantage of this is obvious, but the advantage is that I can make optimisations that are specific to my current use case.

For day 5 there was an interesting task to do. Lifting crates with a virtual crane, and placing them on other stacks of crates, in a particular order. Essentially you have a bunch of LIFO stacks and you have to pop and push from them in a particular order.

Parsing the input for this task was a little bit annoying, because there's a kind of ascii art representation of the stacks at the start. It looks nice, but it's not the most helpful thing for machine readability. Here's the example they provide:

    [D]    
[N] [C]    
[Z] [M] [P]
 1   2   3 

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

The first thing I do for day 5 is count up all the crates. This total is going to be the biggest any of my stacks could possibly get. So I reserve that much space for each stack. Then I put the character that represents each container into my freshly allocated LIFOs in the right order.

I decided that I wouldn't bother to track how many items were in each LIFO, since they were not going to get particularly big anyway. So what I did was make sure that the remaining elements in a LIFO were all spaces, so that I can find the top by scanning along until I hit a space.

In hindsight this wasn't a great idea. It's not fast at all, and it only saves about 9 bytes of memory, I had plenty to spare, actually. Anyway, the second part of the task asked me to pop multiple items at once from a LIFO. I hadn't planned for this when I wrote the solution to part 1, so I got a bit lazy, and this made the solution really slow.

The problem was that the items that I popped from one LIFO now needed to be pushed onto the next LIFO in reverse order (or in the same order, depending on how you look at it). There's a much better way to do this, but my solution was simply to move the items to a temporary LIFO, and then move them out of there onto the target. This one goes really slow. It takes about fifteen minutes to finish computing both results for this one. I need to go back and optimise my solution for day 5 at some point.

Full listing on GitHub

Part of a series of posts: Next in series >