hash - Diff of hashes with a correction factor in Ruby for dynamic hashes -
similar question how create diff of hashes correction factor? want compare hashes inside array hashes can 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 number determines how many keys/values should match consider matched. want diff function returns both matched , 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 |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
Comments
Post a Comment