开发者

Diff of hashes with a correction factor in Ruby for dynamic hashes

Similar to this question How do I create a diff of hashes with a correction factor? I want to compare the hashes inside an array but the hashes can be dynamic.

h_array = [
   {:roll => "1", :name => "saroj", :class => "mscit"}, 
   {:name => "saroj", :class => "Mscit", :roll => "12", :attendance => "P"}, 
   {:class => "Mscit", :roll => "12", :name => "saroj", :attendance => "F", :remarks => "something"}
]

get_diff(h_array, correct_factor = 2)
# should return
# matched :: {:class=>"Mscit", :roll=>"12", :name=>"saroj"},
# unmatched :: {:attendance=>"F", :remarks=>"something"}

get_diff(h_array, correct_factor = 3)
# should return 
# matched :: {:name=>"saroj"},
# unmatched :: {:class=>"Mscit", :roll=>"12", :attendance=>"F", :remarks=>"something"}

The correct_factor is the number that determines 开发者_JAVA百科how many keys/values should match to consider it is matched. What I want is a diff function which returns both matched and unmatched pair.


def get_diff(input,correct_factor)
    input_hash_merged = Hash.new
    solution_hash = Hash.new
    input.select{ |x| input_hash_merged.merge!(x) }
    input_hash_merged.each do |k,v|
        arr = Array.new
        freq = Hash.new(0)
        input.select{ |x| arr << x[k] unless x[k].nil? }
        arr.select{ |x| freq[x] += 1 }
        max_element = arr.sort_by { |x| freq[x] }.last
        max_count = freq.values.sort.last
        solution_hash[k] = max_element unless max_count < correct_factor
    end
    unmatched_hash = input_hash_merged.reject{|k,v| !solution_hash[k].nil?} 
    p solution_hash
    p unmatched_hash
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜