2013-09-11 39 views
-1

我试图找到一个模式,而不使用哈希,但现在不知道是否有可能,所以我想知道如果有人可以帮助我翻译我的附近工作数组代码,进入哈希模式,使其工作。用红宝石代码替代工作阵列代码在红宝石找到模式

我已经看到了一个较短的解决方案,我将发布,但我不太关注它,我希望这个翻译将帮助我更好地理解哈希。

这里是我的代码,以我的意见 - 我已经加粗,我知道就不行,因为我比较的频率值的一部分,一个元素本身

@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]) 

的价值现在我看了这个帖子: Ruby: How to find item in array which has the most occurrences?

而且看着这个代码

arr = [1, 1, 1, 2, 3] 
freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h } 
arr.sort_by { |v| freq[v] }.last 

,但我不很明白。

我想让我的代码做的是,因为它发现最常见的元素,
将该元素存储为键,并将其频率作为其值存储。
然后我想下一个元素频率比较现有的对的频率,
如果它等于最频繁的,它保存为好,
如果是较大的,取代现有的,
如果它小于,忽略并移动到下一个元素。

当然,我想返回频率最高的元素,而不是频率的数量,如果两个或多个元素共享最多的频率,然后找到这些数字的平均值。

我很想看到它,提供了一些我的数组尝试,也许是我上面发布的散列方法的解释,或者是更简单一点的散列方法的解释。

回答

0

这似乎适合您的要求:

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 

它创建频率histogram,其中所述键是输入数组的元素的哈希和的值是数组中该元素的频率。然后,它将删除除最常见的元素之外的所有元素。最后,它平均剩余的密钥。

+0

完美。如果有人想要返回双峰或多峰的答案,可以缩短返回行至: most_frequent.keys – sage