The gravity language operates on a stack and has three basic operations:
- Zi sets the i th element of the stack to zero
- Ii increments the i th element by one
- Ji,j compares the i th and j th elements and jumps if not equal
The stack looks like this:
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7
Assume you want to write an algorithm that compares two numbers and returns 1
if the former is greater than the latter. Let's pick 2
and 3
. You can load
the number 2
on the stack like this:
- Z0
- I0
- I0
+---+---+---+---+---+---+---+---+
| 2 | | | | | | | |
+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7
This will load the number 3
on the stack:
- Z1
- I1
- I1
- I1
+---+---+---+---+---+---+---+---+
| 2 | 3 | | | | | | |
+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7
We can compare the numbers in position 0
and 1
and if they're different we
jump and execute a different instruction:
- Z4
- J0,1 JUMP TO 4
- END
- I4
- END
+---+---+---+---+---+---+---+---+
| 2 | 3 | | | 1 | | | |
+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7
Great, we just compared 2 numbers!
You're now familiar with the gravity language. Can you write an algorithm that sums two numbers?