Last active
July 9, 2019 10:01
-
-
Save Bablzz/d32fec7a7d7cb9f169c4c633a4d77ffb to your computer and use it in GitHub Desktop.
Greedy algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Set cover problem | |
states = ['mt', 'wa', 'or', 'id', 'nv', 'ut', 'ca', 'az'].uniq | |
station = {} | |
station["kone"] = ['id', 'nv', 'ut'].uniq | |
station["ktwo"] = ['mt', 'wa', 'id'].uniq | |
station["kthree"] = ['or', 'nv', 'ca'].uniq | |
station["kfour"] = ['nv', 'ut'].uniq | |
station["kfive"] = ['ca', 'az'].uniq | |
final_station = [] | |
covered = [] | |
until states.empty? | |
best_station = '' | |
states_covered = [] | |
station.each do |index, s| | |
covered = states & s | |
if covered.length > states_covered.length | |
best_station = index | |
states_covered = covered | |
end | |
end | |
states = states - states_covered | |
final_station << best_station | |
end | |
puts final_station | |
# => kone | |
# ktwo | |
# kthree | |
# kfive | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment