Skip to content

Instantly share code, notes, and snippets.

@Bablzz
Last active July 9, 2019 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bablzz/d32fec7a7d7cb9f169c4c633a4d77ffb to your computer and use it in GitHub Desktop.
Save Bablzz/d32fec7a7d7cb9f169c4c633a4d77ffb to your computer and use it in GitHub Desktop.
Greedy algorithm
# 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