algorithmlittle-man-computer

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

  • Your code correctly outputs the minimum value, but:

    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:

    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/lmc@v0.816/lmc.js"></script>