40 lines
1.1 KiB
Text
40 lines
1.1 KiB
Text
with javascript_semantics
|
|
function mode(sequence s)
|
|
-- returns a list of the most common values, each of which occurs the same number of times
|
|
integer nxt = 1, count = 1, maxc = 1
|
|
sequence res = {}
|
|
if length(s)!=0 then
|
|
s = sort(s)
|
|
object prev = s[1]
|
|
for i=2 to length(s) do
|
|
if s[i]!=prev then
|
|
s[nxt] = {count,prev}
|
|
nxt += 1
|
|
prev = s[i]
|
|
count = 1
|
|
else
|
|
count += 1
|
|
if count>maxc then
|
|
maxc = count
|
|
end if
|
|
end if
|
|
end for
|
|
s[nxt] = {count,prev}
|
|
res = ""
|
|
for i=1 to nxt do
|
|
if s[i][1]=maxc then
|
|
res = append(res,s[i][2])
|
|
end if
|
|
end for
|
|
end if
|
|
return res
|
|
end function
|
|
|
|
?mode({1, 2, 5, -5, -9.5, 3.14159})
|
|
?mode({ 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" })
|
|
?mode({1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6})
|
|
?mode({.2, .7, .1, .8, .2})
|
|
?mode({"two", 7, 1, 8, "two", 8})
|
|
?mode("Hello there world")
|
|
?mode({})
|
|
{} = wait_key()
|