CS 202 - "Runlong" contest results (HW 3, problem 1d)
Most of you submitted correct solutions for the runlong problem, that
is, programs that run for a finite number of steps without
encountering a "bneg" instruction and stop by executing the "halt"
command. Some tried to provide more than 24 instructions, but recall
that the entire program needs to fit into the 24 bytes of ROM.
The programs that worked correctly and ran for more than 24 steps are:
- 12,194 steps Tianxiao Wang 2
- 2,429 steps Scharstein 2
- 326 steps Scharstein 1
- 275 steps Semi Doken
- 226 steps Tianxiao Wang
- 206 steps Hamza Usmani
- 170 steps Toby Norden
- 123 steps Cole Simon
- 78 steps Greg Bassell
- 66 steps Derek Sakamoto
- 64 steps Ling Fang
- 33 steps Chris Anderson
- 32 steps Macky Franklin
- 30 steps Matt Park
- 29 steps Kelvin Gorekor
Congratulations to all, and especially to Tianxiao, who beat both of
my own programs!
There are many ways to solve this problem, but all involve writing
"self-modifying code". That is, your program has to store some instructions
in RAM and then execute them.
In the simplest case the program stores the instruction "halt" in the last
byte of RAM (0x1f) as follows:
0: 0x82 b 2 /* jump around the next instruction */
1: 0xff /* the opcode for halt - not executed */
2: 0x01 ld A, 1 /* load the opcode for halt... */
3: 0x7f st A, 0x1f /* ...and store it at the end of RAM */
This program runs for 31 steps (assuming the RAM is initially all 0,
which you should not generally assume). Most steps execute opcode
0x00, i.e., the "harmless" opcode "ld A, 0". To get 32 steps you have
to disguise the data (i.e., the halt opcode) using instructions, for
example as the difference of two harmless opcodes. To run for more
than 32 steps, you need to implement some sort of self-modifying loop.
There are many possibilities, including the following two:
- Store the opcode for branch (b) in RAM, and each time through
the loop change it to jump to a different location, until you jump to
a halt instruction.
- Store a "harmless" instruction in RAM (e.g., ld, add, sub), and change
it everytime in a loop until it turns into a halt instruction.
Contest extension!
Now that you see what's possible, and also have an idea of how it could
be done, can you beat the current front-runner, or at least my own programs?
I'll accept new entries anytime, until midnight on Sunday
10/7. Simply email me the text file with the opcodes in hex.