ruby 编写一种方法模式,该模式将数字数组作为输入,并返回最常用值的数组。如果只有一个 -

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 编写一种方法模式,该模式将数字数组作为输入,并返回最常用值的数组。如果只有一个 -相关的知识,希望对你有一定的参考价值。


def mode(array)
  array_of_modes = []
#NOTE:
#Hash.new(0) differs from defining an empty hash by {} in that:
#      1. Hash.new(0) defines an empty hash with a default value of 0 for new keys with undefined values.
#      2. {} defines an empty hash that will default to nil for new keys with undefined values.
#Here, executing the block on nil will result in NoMethodError as + is undefined for nil, so must  Hash.new(0)

##############CREATE OUR FREQUENCIES HASH#########
  frequencies = array.each_with_object(Hash.new(0)){|key, hash| hash[key] += 1}
# NOTE:
# Using #each_with_object(Hash.new(0)) iterates the specified block for each array element with the object (i.e., the empty hash)

 # #each_with_object(obejct) always returns the given object. returns the our new hash "frequences", populated with the array element, frequency pairs.

##############DETERMINE THE COUNT OF THE HIGHEST FREQUENCY#################
  highest_frequency = frequencies.invert.sort.last.first
# breakdown when running on array: [1, 4, 3, 5, 6, 7, 8, 2, 1, 5, 6, 5, 3, 3, 3, 5]
#frequencies #{1=>2, 4=>1, 3=>4, 5=>4, 6=>2, 7=>1, 8=>1, 2=>1}
#frequencies.invert #{2=>6, 1=>2, 4=>5} --> swap values as keys; 4=>3 gets overridden by redefining 4=>5
#frequencies.invert.sort #[[1, 2], [2, 6], [4, 5]] --> can't sort a by pair, but can sort based on hash key to a 2D array of the key/value pairs
#print frequencies.invert.sort.last --> snag the last element array that holds the elements telling us [highest frequency, a mode value], but there may be more than one mode
#print frequencies.invert.sort.last.first --> snag the first element we know tells us frequency of mode

#######USE FREQUENCY HASH TO COMPARE FREQs OF THE ARRAY ELS TO HIGHEST FREQUENCY######
  frequencies.each_pair do |el, count|
    array_of_modes << el if count == highest_frequency #push any keys with values matching the highest frequency to the array of modes
  end
  return array_of_modes
end



# I didn't complete this challenge to the extent of the required challenges to include refactoring the code, etc. 
# I'm running out of time to submit that this evening but I wanted to post what I learned from the work that I did. 
# I spent a good amount of time deciphering the above code that I was having a tough time working through. Through the 
# process I learned some new methods and gained a better understanding of ones we have been using often. 

以上是关于ruby 编写一种方法模式,该模式将数字数组作为输入,并返回最常用值的数组。如果只有一个 -的主要内容,如果未能解决你的问题,请参考以下文章

c++打印数字图案?

ruby 练习:计算数字数组的中位数写一个方法中位数,它取一个数字数组作为输入并返回

Ubuntu命令行模式与图形桌面切换方法

具有 2 个(或更多)模式类型的 mongoose 数组

模板方法设计模式

【JS】数组对象自定义排序