[comp.lang.forth] Need Forth Sort

tbg@apollo.UUCP (04/07/87)

    Anybody have a definition of a word that will 
    sort 4 integers on the stack?  I need one and I'm
    very surprised that none of the books I've got
    has one.  Of course I could write one myself but
    I thought it would be a fun use of comp.lang.forth.

    Actually what I need is something that will check 
    four words on the stack to see if at least three
    of them are approximately equal, and return the
    average of the approximately equal ones and a flag
    indicating whether there were at least 3 approximately
    equal values found (or garbage and a flag indicating
    that there were not 3 values approximately equal).
    
    Speed is important.  The value used to test for
    "approximately equal" could be either a variable or
    passed as an argument, whichever is faster.  I think
    an easy way to check for 3 approximately equal values
    would be to sort the 4 values first, so that's why
    I need a sort routine.  Maybe I have the basis of
    a Dr. Dobb's article here, if it hasn't all been 
    written about before.

/tom

drw@cullvax.UUCP (04/08/87)

tbg@apollo.uucp (Tom Gross) writes:
>     Actually what I need is something that will check 
>     four words on the stack to see if at least three
>     of them are approximately equal, and return the
>     average of the approximately equal ones and a flag
>     indicating whether there were at least 3 approximately
>     equal values found (or garbage and a flag indicating
>     that there were not 3 values approximately equal).

Don't bother to sort the values.  That will take a theoretical minimum
of 5 comparisons, whereas testing all pairs for approximate equality
will only take 6.  (Assuming that approximate equality testing is not
much slower than greater/less testing.)  Test all 6 pairs
(straight-line code) for approximate equality, and keep count of the
number of pairs that pass.  If at least 3 pairs pass, then you have a
good case.  But...

If the 4 numbers are A, B, C, and D, it could be that the following
sets of pairs test approximately equal:

Case 1: AB BC AC (so D's the odd man out)

Case 2: AB BC CD (because A and D are just a little too far apart)

Determining the average value can be tricky, because you aren't
guaranteed that there is a uniquely defined set of values all of which
are approximately equal to each other, and none of which are
approximately equal to anything outside the set.  E.g., in case 2
above, which numbers do you average?

And why is your text indented 5 spaces?  It's a waste!

Dale
-- 
Dale Worley		Cullinet Software
UUCP: ...!seismo!harvard!mit-eddie!cullvax!drw
ARPA: cullvax!drw@eddie.mit.edu
Un*x (a generic name for a class of OS's) != Unix (AT&T's brand of such)