Rebol3 Code Examplex
Averages/Mode
Find the most frequently occurring value in a set of numbers.
Rebol [
title: "Rosetta code: Averages/Mode"
file: %Averages-Mode.r3
url: https://rosettacode.org/wiki/Averages/Mode
]
modes: function [
"Returns the most frequently occurring item(s) in a series."
data [series!] "Input series (will not be modified)"
][
sorted: sort copy data
cur-val: first sorted ;; seed with first value
cur-count: 1 ;; current run
best-count: 0 ;; highest frequency seen so far
result: copy []
foreach val next sorted [
either val == cur-val [
++ cur-count ;; extend current run
][
case [
cur-count > best-count [ ;; new sole mode
best-count: cur-count
append clear result cur-val
]
cur-count == best-count [ ;; tie: add to modes
append result cur-val
]
]
cur-val: val ;; start new run
cur-count: 1
]
]
;; flush the final run
case [
cur-count > best-count [ reduce [cur-val] ]
cur-count == best-count [ append result cur-val ]
'else [ result ]
]
]
; mode tests:
num-gen: func[n][ collect [loop n [keep random n]] ]
foreach n [5 10 15 20] [
print ["^/Numbers:" mold x: num-gen n]
print ["Sorted: " mold sort x]
print ["Count:" n "Mode(s):" mold modes x]
]Output:
Numbers: [1 1 4 3 4]
Sorted: [1 1 3 4 4]
Count: 5 Mode(s): [1 4]
Numbers: [5 1 10 6 9 4 7 4 7 3]
Sorted: [1 3 4 4 5 6 7 7 9 10]
Count: 10 Mode(s): [4 7]
Numbers: [7 11 6 8 15 3 10 2 8 7 7 8 8 14 15]
Sorted: [2 3 6 7 7 7 8 8 8 8 10 11 14 15 15]
Count: 15 Mode(s): [8]
Numbers: [10 8 12 20 4 14 10 3 6 16 1 12 8 5 2 14 14 6 1 12]
Sorted: [1 1 2 3 4 5 6 6 8 8 10 10 12 12 12 14 14 14 16 20]
Count: 20 Mode(s): [12 14]