Re: minmax implementation

new topic     » goto parent     » topic index » view thread      » older message » newer message

Jason Gade wrote:
> 
> Sorry for the triple post. Here's a (tested) implementation. I should probably
> comment it better.
> 
> }}}
<eucode>
> --minmax.e
> constant GREATER = 1,
>          LESS = -1
> 
> -- returns a sequence containing the minimum or maximum element and its index
> -- or an empty sequence if there are no elements.
> -- s is the sequence to check
> -- relate is -1, 0, or 1 to check against the result of compare()
> function minmax(sequence s, integer relate)
>     object x
>     integer index
> 
>     if length(s) >= 1 then
>         x = s[1]
> 	index = 1
>         for i = 2 to length(s) do
>             if compare(s[i], x) = relate then
>                 x = s[i]
>                 index = i
>             end if
>         end for
> 
>         return {x, index}
>     else
>         return {}
>     end if
> 
> end function -- minmax
> 
> global function min(sequence s)
>     return minmax(s, LESS)
> end function -- min
> 
> global function max(sequence s)
>     return minmax(s, GREATER)
> end function -- max
> </eucode>
{{{

> 
> --
> "Any programming problem can be solved by adding a level of indirection."
> --anonymous
> "Any performance problem can be solved by removing a level of indirection."
> --M. Haertel
> "Premature optimization is the root of all evil in programming."
> --C.A.R. Hoare
> j.

How nice! eeeeek!
1/ Passing everything as arguments wastes time, since the vars that hold routine
arguments are uninitialised twice. Better use local vars, which don't have that
drawback. This will worsen when the extra argument (starting point) suggested by
Juergen comes in.
2/ You create a temporary on return from the routine, and the user next has to
say index=returned[1] or similar. Too much typing and more waste, sorry.

CChris

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu