Skip to content

Instantly share code, notes, and snippets.

@sobinsunny
Created October 26, 2016 03:36
Show Gist options
  • Save sobinsunny/1f18668b6ed9ff4db6bcbe3006e3ff3b to your computer and use it in GitHub Desktop.
Save sobinsunny/1f18668b6ed9ff4db6bcbe3006e3ff3b to your computer and use it in GitHub Desktop.
modified
# Ruby 2.3.1
class WebPageRank
MAX_WEIGHT = 8
def initialize
# read input from file
@file = File.read('input.txt')
end
def process_input_file
input_array = @file.split(/\n+/)
@query_index = 0
@page_index = 0
@page_hash = {}
@query_result_hash = {}
input_array.each_with_index do |input|
input.downcase!
next if input.strip.empty?
if input.start_with? 'p'
process_page_input(input)
else
process_query_input(input)
end
end
display_rank_result
end
def process_page_input(page_input)
@page_hash[page_name] = make_weighted_keyword_hash(page_input)
end
def process_query_input(query_input)
@query_result_hash[query_name] = calculate_page_weight(query_input)
end
def calculate_page_weight(query_input)
weighted_hash = make_weighted_keyword_hash(query_input)
query_hash = {}
@page_hash.each do |_key, value|
query_hash[_key] = calaculate_page_weight(value, weighted_hash)
end
query_hash
end
def display_rank_result
@query_result_hash.each do |key, value|
puts "#{key} : #{sorted_page_array(value)}"
end
end
private
def calaculate_page_weight(value, weighted_hash)
weighted_hash.map { |_key, weight| value.key?(_key) ? value[_key] * weight : 0 }.reduce(:+)
end
def make_weighted_keyword_hash(input)
input.split(' ').drop(1).each_with_index.map { |key, index| [key, MAX_WEIGHT - index] }.to_h
end
def query_name
@query_index+=1
('Q' + @query_index.to_s).to_sym
end
def page_name
@page_index+=1
('P' + @page_index.to_s).to_sym
end
def sorted_page_array(page_hash)
page_hash.sort_by { |_, value| value * -1 }.to_h.select { |_, value| value > 0 }.keys.join(' ')
end
end
w = WebPageRank.new
w.process_input_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment