Display the Two Maximum Numbers in a List in Oz Programming language

170 views Asked by At

I need to make a program that displays the two maximum numbers in a list using Oz programming language. I have the code for printing the maximum number in a list, but I need the two biggest numbers. Here is what I have so far:

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]}}

This will display the biggest number in the list, but only one and I need the two biggest numbers to display. What do I need to do?

1

There are 1 answers

0
rbi On

There are many ways in Mozart-Oz to solve that problem. This is one possible solution which is extended to a list of size (length) N; however, only works for possitive numbers.

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

Notice the behavior of MaxN, when N is greater than the length of the list of numbers L1, the browser displays a list of length L1 with the first N biggest numbers. Negative numbers are replaced by zero. I hope this is still useful.