-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:出現回数が最も多い配列内のアイテムを見つける方法は?

そして、このコードを見て

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

しかし、私はそれをよく理解していません。

コードで実行したいのは、最も頻繁に使用される要素を見つけたときに、
その要素をキーとして保存し、その頻度を値として保存することです。
次に、次の要素の頻度を既存のペアの頻度と比較し、
それが最も頻度の高いものと等しい場合はそれも保存し、
大きい場合は既存のものを置き換え、
小さい場合はそれを置き換えます。 、無視して次の要素に移動します。

それからもちろん、頻度の量ではなく、最も頻度の高い要素を返したいと思います
。2 つ以上の要素が最も多くの頻度を共有している場合は、それらの数値の平均を見つけます。

配列の試みのヒントと、上記で投稿したハッシュメソッドの説明、またはもう少し単純に分解されたものと一緒に見たいと思います。

4

1 に答える 1