Re: Sort items in a list without OSAXen
Re: Sort items in a list without OSAXen
- Subject: Re: Sort items in a list without OSAXen
- From: Nigel Garvey <email@hidden>
- Date: Sun, 2 Sep 2001 13:23:16 +0100
"Joseph A. Weaks" wrote on Sat, 1 Sep 2001 23:54:28 -0500:
>
ASers,
>
>
I have a variable that contains random numbers in a list, say
>
{1,2,3,4}, and I need the sum of the highest three.
>
I don't want to use an OSAX 'sort' command for portability reasons.
>
My approach has been to first sort the list in descending in order
>
which lets me get the sum items 1-3.
Rather than sort the entire list, you can just go through it three times,
finding the highest number, adding this to the score, and eliminating it
for the next repeat.
on sumTop3 from theList
copy theList to listCopy -- to leave the original list intact
set theSum to 0 -- initialise the total
set listLen to (count theList)
repeat 3 times
set highestNum to 0
repeat with i from 1 to listLen
if item i of listCopy > highestNum then
set highestNum to item i of listCopy
set highestPos to i
end if
end repeat
set theSum to theSum + highestNum -- add the highest number
set item highestPos of listCopy to 0 -- eliminate it
end repeat
theSum
end sumTop3
sumTop3 from {9, 1, 3, 4, 10, 6, 5, 7, 2, 1, 1}
--> 26
This doesn't contain any checks for valid lists, but it does produce
reasonable results with lists that only contain one or two numbers. It
also works if any of the highest numbers are duplicated.
NG