Reputation: 1523
In OCaml how would I write a median function that takes 5 arguments and returns the median. For example med5 2 5 7 4 3
would return 4.
I managed to write a med3 function (returns the median of 3 arguments) using if and else statements but this would be ridiculously complex if I attempted the same technique for 5 arguments :(
let med3 a b c =
if ((b<=a && c>=a) || (c<=a && b>=a)) then a
else if ((a<=b && c>=b) || (c<=b && a>=b)) then b else c;;
For the med5 function, I would like to be able to use the min and max functions (built in to OCaml) to discard the highest and lowest values from the set of 5 arguments. Then I could use the med3 function that I have already written to return the median of the remaining 3 arguments, but how do I discard the minimum and maximum arguments!?!?!?!?
Any help would be much appreciated :)
Upvotes: 1
Views: 2247
Reputation: 4415
If lists and arrays are forbidden, you can have three variables storing the three greatest elements among the five:
let med5 a b c d e =
let first = ref min_int in
let second = ref min_int in
let third = ref min_int in
if a >= !first then (third := !second; second := !first; first := a)
else if a >= !second then (third := !second; second := a)
else if a >= !third then (third := a);
if b >= !first then (third := !second; second := !first; first := b)
else if b >= !second then (third := !second; second := b)
else if b >= !third then (third := b);
(* you guess what to do for c, d, e ;-) *)
(* return the third largest element: *)
!third
Upvotes: 0
Reputation: 10148
If you can use Array
, then just put your 5 entries in an array, sort it, and return a[2]
. If it's also forbidden in your assignment, you can use a poor-man's bubble sort to select the max, then the min:
let med5 a b c d e =
(* move the max towards 'e' *)
let a,b = if a<=b then a,b else b,a in
let b,c = if b<=c then b,c else c,b in
...
(* then move the min towards 'd', don't forget to reverse the comparisons *)
...
in med3 a b c
Upvotes: 2
Reputation: 4415
You could put those 5 arguments into a list, then removing an element from a list is easy.
Upvotes: 0