Frequency of occurrence

Given an sequence of integers, return the integer that occurs the most and its frequency of occurrence, as well as the integer that occurs the median number of times and it’s frequency.

 

For example [5,1,1,3,3,3] would have the number 3 occurring 3 times (mode) and would have the number 1 occurring 2 times which is the median number of times.
       Code:
def max_occurence_and_median data
  return false if data.count <1  #return false if array is empty

  h_data = Hash.new(0)

  data.each{|x| h_data[x] +=1}

  h_data = h_data.sort_by { |key, value| value}.reverse.to_h

  max_occurent_value, max_occurence = h_data.first
  median = find_median(h_data.values)
  median_value = h_data.key(median.to_i)

  return"max occurent value #{max_occurent_value} occurence #{max_occurence}, Median #{median} and median  value is #{median_value}"
end

def find_median(arr)
  len = arr.length
  (arr[(len - 1) / 2] + arr[len / 2]) / 2.0
end


puts "Input: [5,5,5,5,1,1,1,1,1,3,3,3,3,3,3,3]"
print "Output: "
data = [5,5,5,5,1,1,1,1,1,3,3,3,3,3,3,3]
puts max_occurence_and_median(data)

puts "Input [5,1,1,3,3,3]"
print "Output: "
data = [5,1,1,3,3,3]
puts max_occurence_and_median(data)

 Output:

###############################################################################################

Input: [5,5,5,5,1,1,1,1,1,3,3,3,3,3,3,3]

Output: max occurent value 3 occurence 7, Median 5.0 and median value is 1

********************************************

Input [5,1,1,3,3,3]

Output: max occurent value 3 occurence 3, Median 2.0 and median value is 1

#################################################################################################

Leave a Reply to BURGERor Cancel reply

Your email address will not be published. Required fields are marked *