Skip to content

Instantly share code, notes, and snippets.

@knjname
Created August 21, 2012 06:17
Show Gist options
  • Save knjname/3412589 to your computer and use it in GitHub Desktop.
Save knjname/3412589 to your computer and use it in GitHub Desktop.
asc = (l,r) -> l - r
med = (list) ->
sorted = [list...].sort(asc)
prev = Math.floor((sorted.length - 1) / 2)
next = Math.ceil((sorted.length - 1) / 2)
(sorted[prev] + sorted[next]) / 2
most = (list) ->
sorted = [[list...].sort(asc)..., NaN]
prev = NaN
count = 0
most = NaN
mostCount = 0
for e in sorted
if prev is e
count++
else
if mostCount < count
most = prev
mostCount = count
count = 0
prev = e
most
# test
console.log [[10..1]..., NaN].sort(asc)
console.log med [1]
console.log med [1,2]
console.log med [1,2,3]
console.log med [1..10]
console.log med [0,1,2,2,3]
console.log med [0,1,3,1,5,6,2,3,5,53,53,12,2131,4,0]
console.log 'most'
console.log most [1,2,3,3,3,3,2,1,2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment