+ "end: sto a 1\n",
+ "\"\"\"\n",
+ "m = new_machine()\n",
+ "program_from_listing(program, m)\n",
+ "run(m)\n",
+ "show_machine(execute(program, initial_state={'a': 9, 'b': 3}))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "set c 0\n",
+ "sto a 1\n",
+ "jpz b 8\n",
+ "dec b\n",
+ "ld a 1\n",
+ "jpz a 4\n",
+ "inc c\n",
+ "dec a\n",
+ "jmp -3\n",
+ "jmp -7\n",
+ "sto a 1\n"
+ ]
+ }
+ ],
+ "source": [
+ "labelled_instructions = [i.strip() for i in program.split('\\n') if i.strip() if not i.strip().startswith('#')]\n",
+ "instructions = replace_labels(labelled_instructions)\n",
+ "print('\\n'.join(instructions))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'1: 0, a: 0, b: 0, c: 10, pc: 13'"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# c holds a * b\n",
+ "program = \"\"\"\n",
+ " set a 2\n",
+ " set b 5\n",
+ " set c 0\n",
+ " sto a 1\n",
+ "loop: jpz b end \n",
+ " dec b\n",
+ " ld a 1\n",
+ "smul: jpz a emul\n",
+ " inc c\n",
+ " dec a\n",
+ " jmp smul\n",
+ "emul: jmp loop \n",