bubble sort + fixed issue when writing to reference in ram.py

This commit is contained in:
Sam Hadow 2024-03-29 22:54:02 +01:00
parent 8b192bf02e
commit 39c5e930ca
3 changed files with 39 additions and 1 deletions

View File

@ -1,5 +1,13 @@
LDFLAGS="-L/usr/local/opt/flex/lib"
bubble_sort: ram
./ram < bubble_sort.asm
echo "### machine.py ###"
cat machine.py
echo "### execution ###"
python machine.py
a_pow_b: ram
./ram < a_pow_b.asm
echo "### machine.py ###"

View File

@ -0,0 +1,30 @@
(20, 17, 18, 26, 8, 19, 9, 11, 12, 28, 13, 7, 21, 15, 29, 14, 1, 16, 3, 22, 4)
ADD(1, 0, r0) // PART 1: copy table to work registries. r0 counter
ADD(1, i0, r1) // upper limit
JE(r0, r1, 5) // loop control
ADD(r0, 3, r2) // r2 copied element destination address, (r0 to r3, reserved registries)
ADD(i@r0, 0, r@r2) // copy element
ADD(1, r0, r0) // increment counter
JUMP(-4) // loop
ADD(i0, 4, r2) // PART 2: bubble sort, counter upper limit
ADD(4, 0, r0) // r0 counter, 1st element to compare
ADD(5, 0, r1) // r1 counter, 2nd element to compare
JE(r1, r2, 8) // inner loop control
JL(r@r1, r@r0, 4) // if 2nd element > 1st element, jump (elements already ordered)
ADD(r@r0, 0, r3) // temp value
ADD(r@r1, 0, r@r0) // replace 2nd element with the 1st
ADD(r3, 0, r@r1) // replace 1st element with the 2nd (stored in temp value)
ADD(1, r0, r0) // increment counter 1st element
ADD(1, r1, r1) // increment counter 2nd element
JUMP(-7) // inner loop
JE(5, r2, 3) // outer loop control
SUB(r2, 1, r2) // decrement upper limit
JUMP(-12) // outer loop
ADD(4, 0, r0) // PART 3: copy table from work registries to output, r0 counter
ADD(4, i0, r1) // upper limit
JE(r0, r1, 5) // loop control
SUB(r0, 3, r2) // r2 copied element destination address, starts from o1
ADD(r@r0, 0, o@r2) // copy element
ADD(1, r0, r0) // increment counter
JUMP(-4) // loop
ADD(i0, 0, o0) // output size in o0

View File

@ -45,7 +45,7 @@ class Ram(object):
raise TypeError("cannot write on value")
elif type_register == "@": # reference
target_index = self.read_register(ref_origin, index)
self.write_register(ref_target, target_index, value)
self.write_register(value, ref_target, target_index)
def op(self, type_op, r1, r2, r3):
self.current += 1