• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Sort items in a list without OSAXen
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Prev by Date: Re: TIDs ahoy (was Re: coercing a list)
  • Next by Date: Tex-Edit, select only HTML lines?
  • Previous by thread: Palm Desktop
  • Next by thread: Re: Sort items in a list without OSAXen
  • Index(es):
    • Date
    • Thread