Programming Praxis – Median Of Five

In today’s Programming Praxis exercise, our goal is to determine to median of five numbers using only six comparisons. Let’s get started, shall we?

A quick import:

import Data.List

I didn’t like the element swapping and nested ifs of the provided algorithm, so I tried to come up with something a litte more in the spirit of functional programming. I was initially worried that the case statement would evaluate all three comparisons when the the first one was false, but some testing revealed that Haskell is lazy enough to skip the second comparison in that case.

median5 :: Ord a => [a] -> a
median5 ~[a',b',c,d',e'] = case (b<c, b<d, d<c) of
        (True, True , _    ) -> min c d
        (True, False, _    ) -> min b e
        (False, _   , True ) -> min c e
        (False, _   , False) -> min b d
    where ((_,b), (d,e)) = order (order a' b') (order d' e')
          order x y = if y < x then (y,x) else (x,y)

All that’s left to do is to verify that all permutations of the numbers 1 to 5 result in 3 as the median.

main :: IO ()
main = print . all ((== 3) . median5) $ permutations [1..5]
About these ads

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: