RosettaCodeData/Task/Averages-Mode/Phix/averages-mode.phix
2016-12-05 23:44:36 +01:00

40 lines
1.1 KiB
Text

function mode(sequence s)
-- returns a list of the most common values, each of which occurs the same number of times
object this
integer nxt = 1, count = 1, maxc = 1
sequence res = {}
if length(s)!=0 then
s = sort(s)
this = s[1]
for i=2 to length(s) do
if s[i]!=this then
s[nxt] = {count,this}
nxt += 1
this = s[i]
count = 1
else
count += 1
if count>maxc then
maxc = count
end if
end if
end for
s[nxt] = {count,this}
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()