Created
August 2, 2018 15:29
-
-
Save DaneWeber/7f2e600382ced1171086230987eb9a13 to your computer and use it in GitHub Desktop.
2018-08-02 Bits, Please! Code Fight
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
def nightRoute(city) | |
final = city.length - 1 | |
hops = {} | |
hops[0] = city[0].each_with_index.map{ |length, island| length == -1 ? nil : [0, island] }.compact | |
(1..final).each do |iter| | |
hops[iter] = hops[iter - 1].map do |path| | |
if path[-1] == final | |
nil | |
else | |
city[path[-1]].each_with_index.map do |length, island| | |
if length == -1 | |
nil | |
elsif path.include?(island) | |
nil | |
else | |
[*path].append(island) | |
end | |
end.compact | |
end | |
end.compact | |
hops[iter].flatten!(1) | |
hops[iter].reject! { |a| [*a].length != [*a].uniq.length } unless hops[iter].nil? | |
end | |
hops.compact! | |
hops.transform_values! do |routes| | |
routes.reject { |route| !route.include?(final) } | |
end | |
routeLengths(city, hops).min | |
end | |
def routeLengths(city, hops) | |
lengths = [] | |
hops.values.each do |routes| | |
routes.each do |route| | |
lengths.append(routeLength(city, route)) | |
end | |
end | |
lengths | |
end | |
def routeLength(city, route) | |
route_length = 0 | |
route.each_cons(2) do | bridge | | |
route_length += city[bridge[0]][bridge[1]] | |
end | |
route_length | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment