在ruby-to-find模式中,用哈希代码替换接近工作的数组代码
我试图在不使用散列的情况下找到一种模式,但现在不知道这是否可能,所以我想知道是否有人可以帮助我将接近正常工作的数组代码转换为散列模式,使其工作 我已经看到了一个简短的解决方案,我将发布,但我不太明白它,我希望这个翻译将帮助我更好地理解散列 这是我的代码,还有我的注释——我用粗体标出了我知道不起作用的部分,因为我将频率值与元素本身的值进行比较在ruby-to-find模式中,用哈希代码替换接近工作的数组代码,ruby,arrays,hash,mode,Ruby,Arrays,Hash,Mode,我试图在不使用散列的情况下找到一种模式,但现在不知道这是否可能,所以我想知道是否有人可以帮助我将接近正常工作的数组代码转换为散列模式,使其工作 我已经看到了一个简短的解决方案,我将发布,但我不太明白它,我希望这个翻译将帮助我更好地理解散列 这是我的代码,还有我的注释——我用粗体标出了我知道不起作用的部分,因为我将频率值与元素本身的值进行比较 @new = [0] def mode(arr) arr.each do |x|
@new = [0]
def mode(arr)
arr.each do |x| #do each element in the array
freq = arr.count(x) #set freq equal to the result of the count of each element
if freq > @new[0] && @new.include?(x) == false #if **frequency of element is greater than the frequency of the first element in @new array** and is not already there
@new.unshift(x) #send that element to the front of the array
@new.pop #and get rid of the element at the end(which was the former most frequent element)
elsif freq == @new[0] && @new.include?(x) == false #else **if frequency of element is equal to the frequency of the first element in @new array** and is not already there
@new << x #send that element to @new array
end
end
if @new.length > 1 #if @new array has multiple elements
@new.inject(:+)/@new.length.to_f #find the average of the elements
end
@new #return the final value
end
mode([2,2,6,9,9,15,15,15])
mode([2,2,2,3,3,3,4,5])
但是我不太明白
我想让我的代码做的是,因为它找到了最频繁的元素,将该元素存储为键,并将其频率存储为其值。
然后我想比较下一个元素的频率和现有元素对的频率,
如果它等于最频繁的,也要存储它,
如果更大,则替换现有的,
如果小于,则忽略并移动到下一个元素 当然,我想返回频率最多的元素,而不是频率的数量,
如果两个或两个以上的元素共享的频率最多,那么就要找出这些数字的平均值
我希望看到一些关于我的数组尝试的提示,也许是对我上面发布的哈希方法的解释,或者是一个更简单的分解方法。这似乎符合您的要求:
def mode(array)
histogram = array.each_with_object(Hash.new(0)) do |element, histogram|
histogram[element] += 1
end
most_frequent = histogram.delete_if do |element, frequency|
frequency < histogram.values.max
end
most_frequent.keys.reduce(&:+) / most_frequent.size.to_f
end
def模式(阵列)
直方图=数组。每个带有_对象(Hash.new(0))do |元素的_,直方图|
直方图[元素]+=1
结束
most_frequency=直方图。删除_如果执行|元素,频率|
频率<直方图.values.max
结束
most_frequency.keys.reduce(&:+)/most_frequency.size.to_f
结束
它创建一个频率的散列
直方图
,其中键是输入数组的元素,值是数组中该元素的频率。然后,除最常见的元素外,它将删除所有元素。最后,它对剩余的关键点进行平均。完美。如果有人想返回双模或多模答案,您可以将返回行缩短为:most_frequency.keys
def mode(array)
histogram = array.each_with_object(Hash.new(0)) do |element, histogram|
histogram[element] += 1
end
most_frequent = histogram.delete_if do |element, frequency|
frequency < histogram.values.max
end
most_frequent.keys.reduce(&:+) / most_frequent.size.to_f
end