【问题标题】:Function that returns the median? (OCaml)返回中位数的函数? (OCaml)
【发布时间】:2012-09-30 20:21:33
【问题描述】:

在 OCaml 中,我将如何编写一个接受 5 个参数并返回中值的中值函数。例如med5 2 5 7 4 3 将返回 4

我设法使用 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 函数,我希望能够使用 min 和 max 函数(OCaml 内置)从 5 个参数集中丢弃最高和最低值。然后我可以使用我已经编写的 med3 函数来返回剩余 3 个参数的中位数,但是如何丢弃最小和最大参数!?!?!?!?

任何帮助将不胜感激:)

【问题讨论】:

  • 除非我记错了,med5 2 5 7 4 34 而不是 3
  • 哈哈,你说的对,谢谢指出:)

标签: ocaml median


【解决方案1】:

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

【讨论】:

  • 不幸的是,我的问题是指定我们不能使用列表的作业的一部分,因为我们不应该了解它们:( 并不是说​​我会知道如何使用要么列出!!! :'(
  • 我还要提一下,这个作业的截止日期已经过去了。
【解决方案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

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 2011-04-11
      • 1970-01-01
      • 2018-03-27
      相关资源
      最近更新 更多