Simple assembler interpreter
Description:
This is the first part of this kata series. Second part is here.
We want to create a simple interpreter of assembler which will support the following instructions:
mov x y
- copiesy
(either a constant value or the content of a register) into registerx
inc x
- increases the content of the registerx
by onedec x
- decreases the content of the registerx
by onejnz x y
- jumps to an instructiony
steps away (positive means forward, negative means backward, y can be a register or a constant), but only ifx
(a constant or a register) is not zero
Register names are alphabetical (letters only). Constants are always integers (positive or negative).
Note: the jnz
instruction moves relative to itself. For example, an offset of -1
would continue at the previous instruction, while an offset of 2
would skip over the next instruction.
The function will take an input list with the sequence of the program instructions and will execute them. The program ends when there are no more instructions to execute, then it returns a dictionary (a table in COBOL) with the contents of the registers.
Also, every inc
/dec
/jnz
on a register will always be preceeded by a mov
on the register first, so you don't need to worry about uninitialized registers.
Example
["mov a 5"; "inc a"; "dec a"; "dec a"; "jnz a -1"; "inc a"]
visualized:
mov a 5
inc a
dec a
dec a
jnz a -1
inc a
The above code will:
- set register
a
to5
, - increase its value by
1
, - decrease its value by
2
, - then decrease its value until it is zero (
jnz a -1
jumps to the previous instruction ifa
is not zero) - and then increase its value by
1
, leaving registera
at1
So, the function should return:
{'a': 1}
This kata is based on the Advent of Code 2016 - day 12
Similar Kata:
Stats:
Created | Apr 3, 2017 |
Published | Apr 3, 2017 |
Warriors Trained | 29416 |
Total Skips | 8376 |
Total Code Submissions | 71903 |
Total Times Completed | 8191 |
Python Completions | 2735 |
JavaScript Completions | 1722 |
PHP Completions | 232 |
Java Completions | 1008 |
Lua Completions | 104 |
CoffeeScript Completions | 15 |
C++ Completions | 793 |
Haskell Completions | 147 |
Julia Completions | 38 |
Kotlin Completions | 178 |
Rust Completions | 474 |
C# Completions | 504 |
Clojure Completions | 41 |
Go Completions | 233 |
Scala Completions | 85 |
Crystal Completions | 12 |
COBOL Completions | 4 |
OCaml Completions | 12 |
C Completions | 138 |
Ruby Completions | 43 |
Total Stars | 1116 |
% of votes with a positive feedback rating | 94% of 1452 |
Total "Very Satisfied" Votes | 1295 |
Total "Somewhat Satisfied" Votes | 133 |
Total "Not Satisfied" Votes | 24 |
Total Rank Assessments | 24 |
Average Assessed Rank | 5 kyu |
Highest Assessed Rank | 4 kyu |
Lowest Assessed Rank | 6 kyu |