Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Write a method mode which takes an Array of numbers
- as its input and returns an Array of the most frequent values.
- If there's only one most-frequent value, it returns a
- single-element Array.
- For example,
- mode([1,2,3,3]) # => [3]
- mode([4.5, 0, 0]) # => [0]
- mode([1.5, -1, 1, 1.5]) # => [1.5]
- mode([1,1,2,2]) # => [1,2]
- mode([1,2,3]) # => [1,2,3], because all occur with
- equal frequency
- def mode(array)
- f = Hash.new(0)
- array.each do |x|
- f[x] += 1
- end
- max = 0
- modes = []
- f.each do |key, value|
- if value > max
- modes = [key]
- max = value
- elsif value == max
- modes.push(key)
- end
- end
- modes
- end
Add Comment
Please, Sign In to add comment