1

I want to write an LMC program to find the difference between twice the median and the smallest of 3 distinct inputs efficiently. I would like some help in figuring out an algorithm for this.

Here is what I have so far:

INPUT 901 - Input first
STO   399 - Store in 99 (a)
INPUT 901 - Input second
STO   398 - Store in 98 (b)
INPUT 901 - Input third
STO   397 - Store in 97 (c)
LOAD  597 - Load 97 (a) 
SUB   298 - Subtract 97 - 98 (a - b)
BRP   8xx - If value positive go to xx (if value is positive a > b else b > a)
LOAD  598 - Load 98 (b)
SUB   299 - Subtract 98 - 99 (b - c)
BRP   8xx - If value positive go to xx (if value is positive b > c else c > b)
LOAD  598 - Load 98 (b) which is the median
ADD   198 - Double to get "twice the median"

I realized at the end of the snippet I didn't know which input was the smallest and was assuming the inputs were already sorted (which they aren't).

I think I will need to somehow sort the inputs from smallest to largest to do this efficiently and determine the smallest input and the median within the same branch.

matsjoyce
  • 5,744
  • 6
  • 31
  • 38

1 Answers1

2

I don't know little-man-computer language, but it doesn't matter, it's an algorithm question.

First of all, you made a little confusion naming the three parameters (first you said that 99 was a, then you said 97 was a).

You must load the three parameters in 99, 98, 97 (say a, b, c). Then, you load 99 (a) and subtract 98 (b) from 99 (a).

If the result is positive (99 is greater than 98), you have to swap 98 and 99, so the smallest between the two is in location 99.

Now load 98 (c) and subtract 97 from it. If the result is positive, swap 97 and 98, so the smallest between the two is in location 98.

Finally, you have the two smallest numbers in 98 and 99 locations, that is the smallest and the median.

Load 99 and subtract 98 from it. If the result is positive, 99 contains the median and 98 the smallest, otherwise the contrary.

Now you can double the median one, and calculate the difference between this number and the smallest.