1

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 :)

4

3 回答 3

2

如果您可以使用Array,那么只需将您的 5 个条目放入一个数组中,对其进行排序,然后返回a[2]。如果你的作业也禁止它,你可以使用穷人的冒泡排序来选择最大值,然后是最小值:

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
于 2012-10-10T12:08:19.460 回答
0

您可以将这 5 个参数放入一个列表中,然后从列表中删除一个元素很容易。

于 2012-10-10T11:36:31.460 回答
0

如果禁止使用列表和数组,则可以使用三个变量来存储五个中最大的三个元素:

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
于 2012-10-10T12:28:11.957 回答