Home > Back-end >  LMC program that will produce the sum of the median and twice the smallest of 3 inputs
LMC program that will produce the sum of the median and twice the smallest of 3 inputs

Time:04-11

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

CodePudding user response:

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 STA that 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, b and c (see the DAT lines at the end)
  • Compare a with b
  • If a > b then swap their values using a temp variable
  • At continue compare b with c
  • If b > c then:
    • Forget about what is in b and put the value of c there
    • Compare that value (b which is also c) with a
    • If b < a then swap a and b with the help of c (a copy of b)
  • Finally perform the calculation a a b and 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>

  • Related