Skip to content

Instantly share code, notes, and snippets.

@lilliealbert
Created March 28, 2013 23:24
Show Gist options
  • Save lilliealbert/5267631 to your computer and use it in GitHub Desktop.
Save lilliealbert/5267631 to your computer and use it in GitHub Desktop.
trying to get to a mode
def mode(array)
frequency_hash = {}
array.each do |index|
frequency_hash[index] = array.count(index)
end
# now we have a hash of { number: frequency }
puts "here's the frequency of each thing, key = number, value = frequency of that number"
puts frequency_hash
# now let's figure out if there are equally frequent items
sorted_values = frequency_hash.values.sort { |x, y| y <=> x }
puts "here are all the values in order"
puts sorted_values
equally_frequent_values = []
sorted_values.each do |x|
if sorted_values[0] == x
equally_frequent_values << x
end
end
equally_frequent_values
end
@lilliealbert
Copy link
Author

here's another version that is also broken
def mode(array)

let's made a hash of numbers and their frequency

frequency_hash = {}
array.each do |index|
frequency_hash[index] = array.count(index)
end

puts frequency_hash

now let's figure out if there are equally frequent items

sorted_values = frequency_hash.values.sort { |x, y| y <=> x }

puts sorted_values.inspect

equally_frequent_values = []

sorted_values.each do |x|
until sorted_values[0] != x
equally_frequent_values << x
end
end

puts equally_frequent_values
end

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