Guest User

Untitled

a guest
Dec 9th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. Write a method mode which takes an Array of numbers
  2. as its input and returns an Array of the most frequent values.
  3.  
  4. If there's only one most-frequent value, it returns a
  5. single-element Array.
  6.  
  7. For example,
  8.  
  9. mode([1,2,3,3]) # => [3]
  10. mode([4.5, 0, 0]) # => [0]
  11. mode([1.5, -1, 1, 1.5]) # => [1.5]
  12. mode([1,1,2,2]) # => [1,2]
  13. mode([1,2,3]) # => [1,2,3], because all occur with
  14. equal frequency
  15.  
  16.  
  17. def mode(array)
  18. f = Hash.new(0)
  19.  
  20. array.each do |x|
  21. f[x] += 1
  22. end
  23.  
  24. max = 0
  25. modes = []
  26. f.each do |key, value|
  27. if value > max
  28. modes = [key]
  29. max = value
  30. elsif value == max
  31. modes.push(key)
  32. end
  33. end
  34.  
  35. modes
  36. end
Add Comment
Please, Sign In to add comment