user2955412
user2955412

Reputation: 227

Pseudo Algorithm that takes 4 inputs and prints the sum of largest/best of three numbers

I need a little help with my assignment in Pseudo codes: Take input of 4 numbers and print the sum of the largest 3 numbers.

For example: inputs: 14, 1, 9, 3 output: 14+9+3 => 26

How can I write an algorithm in pseudo codes of the above task?

So far i have come to this:

input a, b, c, d
declare h1, h2, h3
    if(a>=b && a>=c && a>=d)    h1 = a
    if(b>=a && b>=c && b>=d)    h2 = b
    if(c>=a && c>=b && c>=d)    h3 = c
    if(d>=a && d>=b && d>=c)    h4 = d
print h1+h2+h3

Is this any good?

Upvotes: 2

Views: 4151

Answers (3)

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

  1. Let's say that inputs are in array t.
  2. Let sum = t[0].
  3. Let min = t[0].
  4. For i from 1 to 3 repeat steps 5 and 6:
  5. sum += t[i].
  6. if (min > t[i]) min = t[i].
  7. Return sum - min.

Another approach, which you and Brian presented, boils down to sorting (for n=4 you can do it "manually" like you did, but for larger n it's not a good idea) and then taking the sum.

I prefer approach shown above, because it's guaranteed linear time complexity, scales nicely and it's easy to implement. It does exactly one pass through the input data and can be used if the input is streamed one by one and we don't want to store the inputs in the memory (we want to do it "on the fly"). Sorting can be more expensive than linear (can be nlogn) if there are no assumptions whatsoever about the input data.

Upvotes: 3

user448810
user448810

Reputation: 17866

Use recursion. If the first number in the input is smallest, sum the other three, otherwise rotate the inputs and call recursively. Eventually the smallest number will be a, so the other three are the largest, and you can sum them and return the answer. In pseudocode:

function sum3max(a, b, c, d)
    if a == min(a, b, c, d)
        return b + c + d
    return sum3max(b, c, d, a)

Upvotes: 1

Brian J
Brian J

Reputation: 694

Your pseudo code is off to a good start. But right now you only find the single largest of your four numbers. You would need to repeat two more times (ignoring the largest) to find the 2nd and 3rd largest.

Another clever idea, though, is if you need the 3 largest numbers, your 4th number must be the smallest. Find the smallest number, then add the others.

input a, b, c, d
declare min

// find the smallest
min = a
if (b < min) min = b
if (c < min) min = c
if (d < min) min = d

// the sum of the largest 3 = the sum of all 4 minus the minimum
print a + b + c + d - min

Upvotes: 1

Related Questions