Skip to content

Instantly share code, notes, and snippets.

@kenrett
Created February 23, 2013 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenrett/5018587 to your computer and use it in GitHub Desktop.
Save kenrett/5018587 to your computer and use it in GitHub Desktop.
mode
Exercise: Calculating the array mode
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)
end
@anc1234
Copy link

anc1234 commented Feb 23, 2013

!/usr/bin/ruby

Really verbose but works.

def mode(arr)
h = {}
for i in arr
if !h.has_key?(i)
h[i] = 0
end
h[i] = h[i] + 1
end
mode = []
m = 0
for k in h.keys
if h[k] > m
m = h[k]
mode = [k]
elsif h[k] == m
mode.push(k)
end
end
puts "Mode is " + mode.to_s()
end

mode([1,2,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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment