【问题标题】:Display the Two Maximum Numbers in a List in Oz Programming language用 Oz 编程语言在列表中显示两个最大数
【发布时间】:2020-10-04 23:25:12
【问题描述】:

我需要制作一个程序,使用 Oz 编程语言在列表中显示两个最大数字。我有打印列表中最大数字的代码,但我需要两个最大的数字。这是我目前所拥有的:

fun {Max L1}
 case L1
 of nil then 0
 [] X|Xr then
    if X>{Max Xr} then X
     else {Max Xr}
    end
 end
end
{Browse {Max [1 2 3 4 5 6 7 8 9]}}

这将显示列表中最大的数字,但只有一个,我需要显示最大的两个数字。我需要做什么?

【问题讨论】:

    标签: list max oz


    【解决方案1】:

    Mozart-Oz 中有很多方法可以解决这个问题。这是一种可能的解决方案,它扩展到大小(长度)N 的列表;但是,仅适用于正数。

    proc {LengL Ls N R}
        case Ls
        of nil then N = R
        [] L|Lr then {LengL Lr N+1 R}
        end
    end
    proc {Drop1 L Y R}
        R=case L
        of nil then nil
        [] X|Xr then
            if X\=Y then X|{Drop1 Xr Y}
            else {Drop1 Xr Y}
            end
        end
    end
    proc {MaxN L1 N R1}
        proc {Max1 L R}
            R=case L
              of nil then 0
              [] X|Xr then
                  if X>{Max1 Xr} then X
                  else {Max1 Xr}
                  end
              end
        end
        R2={Max1 L1} Lg={LengL L1 0} in
        R1={proc {$ R}
                R=if N==0 then nil
                  elseif N>Lg then R2|{MaxN {Drop1 L1 R2} Lg-1}
                  else R2|{MaxN {Drop1 L1 R2} N-1}
                  end
           end}
    end
    {Browse {MaxN [~11 2 3 4 15 6 7 8 9] 12}}
    

    注意 MaxN 的行为,当 N 大于数字列表 L1 的长度时,浏览器会显示长度为 L1 的列表,其中前 N 个最大数字。负数被零替换。我希望这仍然有用。

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      相关资源
      最近更新 更多