From 39c5e930ca99ae13e57720b71c4cf368d6080d54 Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Fri, 29 Mar 2024 22:54:02 +0100 Subject: [PATCH] bubble sort + fixed issue when writing to reference in ram.py --- src/Makefile | 8 ++++++++ src/bubble_sort.asm | 30 ++++++++++++++++++++++++++++++ src/ram.py | 2 +- 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index 9a88b4b..3614a3c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -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 ###" diff --git a/src/bubble_sort.asm b/src/bubble_sort.asm index e69de29..e0ea202 100644 --- a/src/bubble_sort.asm +++ b/src/bubble_sort.asm @@ -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 diff --git a/src/ram.py b/src/ram.py index 6367c9a..a82f9ab 100644 --- a/src/ram.py +++ b/src/ram.py @@ -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