Averages/Median: Difference between revisions
m
→{{header|AppleScript}}: Corrected "By iteration" solution, which was returning random results with even list counts. Tidied "Quickselect".
No edit summary |
m (→{{header|AppleScript}}: Corrected "By iteration" solution, which was returning random results with even list counts. Tidied "Quickselect".) |
||
Line 191:
=={{header|AppleScript}}==
===By iteration===
<lang
set med to medi(alist)
Line 200 ⟶ 198:
set temp to {}
set lcount to count
if lcount is equal to 2 then
return ((item
else if lcount is less than 2 then
return item 1 of alist
Line 238 ⟶ 236:
end findmax</lang>
{{output}}
<lang applescript>3.5</lang>
===Composing functionally===
Line 355 ⟶ 356:
===Quickselect===
<lang applescript>-- Return the median value of items l thru r of a list of numbers.
if (theList is {}) then return theList
script o
property lst : theList's items l thru r -- Copy of the range to be searched.
end script
set
set m to (
set {l, r} to {1, rangeLength} -- Outer partition indices.
▲ set previousR to listLength
▲ repeat -- quickselect iteration.
set pivot to o's lst's item ((l + r) div 2)
set i to l
set j to r
repeat until (i > j)
set
repeat while (
set i to i + 1
set
end repeat
set
repeat while (
set j to j - 1
set
end repeat
if (i > j) then
else
set o's lst's item i to
set o's lst's item j to
set i to i + 1
set j to j - 1
Line 400 ⟶ 394:
end repeat
--
-- Otherwise reset to partition the partition containing m.
if (j < m) then
if (i > m) then exit repeat
set l to i
else
set previousR to r
set r to j
end if
end repeat
set median to item m of o's lst
-- If the
-- with the median just obtained. We only need to search to the end of the range just partitioned —
if (listLength mod 2 is 0) then▼
set median2 to item (m + 1) of o's lst▼
▲ -- It's only necessary to search to the end of the current partition — unless that's m itself, in which case to end of the most recent partition to its right (if any).
if (r = m) then set r to previousR
repeat with i from (
set
if (
end repeat
set median to (median + median2) / 2
Line 430 ⟶ 423:
-- Demo:
local testList
set testList to {}
repeat with i from 1 to 8
set end of
end repeat
▲return {|numbers|:testList, median:m}</lang>
{{output}}
|