2012-10-10 30 views
1

在OCaml中,我将如何编写一个需要5个参数并返回中位数的中值函数。例如med5 2 5 7 4 3将返回。返回中位数的函数? (OCaml)

我设法使用if和else语句来写一个函数med3(返回的3个参数的值),但如果我尝试相同的技术用于5个参数:(

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;; 

对于这将是可笑的复杂med5功能,我希望能够使用最小和最大函数(内置于OCaml)放弃5个参数集中的最高和最低值,然后我可以使用我已经写好的med3函数返回其余3个参数的中位数,但我该如何放弃最小和最大参数!?!?!?!?

任何帮助将不胜感激:)

+0

除非我记错了,'med5 2 5 7 4 3'是'4',而不是'3' – Virgile

+0

哈哈,你绝对正确的,感谢指出了这一点:) – brnby

回答

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 
0

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

+0

不幸的是我的问题是一项任务的一部分,它指定我们不能使用列表,因为我们不应该了解他们:(不是我会知道如何编写函数列出要么! :'( – brnby

+0

我还应该提到,这项任务的截止日期已经过去了。 – brnby

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