'LMC program that will produce the sum of the median and twice the smallest of 3 inputs
so I've been tasked to create a little-man-machine program that will take 3 distinct inputs and produce the result of the median + 2 * the smallest number.
So far I've managed to produce an output that produces the smallest number of the 3 inputs. How would I go about finding the median and then adding it to 2 * the smallest number?
00 INP
01 STA 99
02 INP
03 STA 98
04 INP
05 STA 97
06 LDA 99
07 SUB 98
08 BRP 12
09 LDA 99
10 STA 98
11 BRP 14
12 LDA 98
13 STA 99
14 LDA 99
15 SUB 97
16 BRP 20
17 LDA 98
18 STA 97
19 BRP 22
20 LDA 97
21 STA 99
22 LDA 99
23 SUB 98
24 BRA 28
25 LDA 98
26 STA 99
27 BRA 30
28 LDA 99
29 STA 98
30 OUT
31 HLT
Solution 1:[1]
Your code correctly outputs the minimum value, but:
- It destroys the other input values, which you still need
- There is some code that never executes (lines 25-27)
- The result of the subtraction at line 23 is not used
- The
STAthat happens at line 29 is useless
I would suggest to first sort the three input values, and then it is easy to apply the "formula" that is requested.
Also: use labels in your program and define the addresses of your variables with DAT codes. Most LMC simulators support labels and it makes the code more readable.
Here is how you could do it. I didn't add comments to the code, as the simulator that you use does not support comments (a pity!), but here is how it works:
- Name the inputs
a,bandc(see theDATlines at the end) - Compare
awithb - If
a > bthen swap their values using atempvariable - At
continuecomparebwithc - If
b > cthen:- Forget about what is in
band put the value ofcthere - Compare that value (
bwhich is alsoc) witha - If
b < athen swapaandbwith the help ofc(a copy ofb)
- Forget about what is in
- Finally perform the calculation
a+a+band output it.
Here is the snippet -- click Run code snippet to activate the inline LMC simulator and control it with the input-box and buttons that will appear:
start INP
STA a
INP
STA b
INP
STA c
LDA b
SUB a
BRP continue
LDA b
STA temp
LDA a
STA b
LDA temp
STA a
continue LDA c
SUB b
BRP output
LDA c
STA b
SUB a
BRP output
LDA a
STA b
LDA c
STA a
output LDA a
ADD a
ADD b
OUT
HLT
a DAT
b DAT
c DAT
temp DAT
<script src="https://cdn.jsdelivr.net/gh/trincot/[email protected]/lmc.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | trincot |
