I suck at math and I need a little code that will start with a list of numbers, pick out the largest number and remove it from that list and place it in a new list then do the same thing with the remaining numbers until the first list is empty and the new list has all the numbers in order from largest to smallest. I know some one will have a real simple solution for this but it’s frying my brain beleive it or not. :oops:
Try something like this…
set theInput to {47, 7, 1, 8, 47, 2, 0, 36, 5, 92, 6, 47}
set theOutput to {}
repeat with tmpInput in theInput
set tmpInput to (tmpInput as number)
set shouldAdd to true
repeat with tmpIndex from 1 to (count theOutput)
set tmpOutput to (item tmpIndex of theOutput) as number
if tmpInput > tmpOutput then
if tmpIndex = 1 then
copy tmpInput to the beginning of theOutput
else if tmpIndex = (count theOutput) then
copy tmpInput to the end of theOutput
else
set theOutput to (items 1 through (tmpIndex - 1) of theOutput) & tmpInput & (items tmpIndex through -1 of theOutput)
end if
set shouldAdd to false
exit repeat
else if tmpInput = tmpOutput then --> Remove multiple occurrences
set shouldAdd to false
exit repeat
end if
end repeat
if shouldAdd then copy tmpInput to the end of theOutput
end repeat
return theOutput
j
To sort a list using the List library from AppleMods:
-- auto-generated library loading code
property _Loader : run application "LoaderServer"
----------------------------------------------------------------------
-- DEPENDENCIES
property _List : missing value
on __load__(loader)
set _List to loader's loadLib("List")
end __load__
----------------------------------------------------------------------
__load__(_Loader's makeLoader())
-- main code
set lst to {2, 6, 8, 7, 1}
return reverse of _List's sortList(lst)
--> {8, 7, 6, 2, 1}
If you’ve not used AppleMods’ libraries before, you’ll need to download and install AppleMods’ Loader system first. Run the Loader installer, then download and add the List library to the ASLibraries folder. You can use the LoaderWizard applet to generate the library loading code to paste at the top of your script.
This works for me:
set lst to {47, 7, 1, 8, 47, 2, 0, 36, 5, 92, 6, 47}
set {saveDelims, text item delimiters} to {text item delimiters, ASCII character (10)}
set x to do shell script "echo "" & (lst as text) & ""|sort -rn"
set text item delimiters to ASCII character (13)
set sortedList to text items of x
repeat with i from 1 to count sortedList
set item i of sortedList to (item i of sortedList) as integer
end repeat
set text item delimiters to saveDelims
sortedList
-->{92, 47, 47, 47, 36, 8, 7, 6, 5, 2, 1, 0}
Hope that’s of some use…
- Dan
Oops - if you want to weed out dupes, in above code replace
set x to do shell script "echo "" & (lst as text) & ""|sort -rn"
with
set x to do shell script "echo "" & (lst as text) & ""|sort -rn|uniq"
-Dan