Jump to content
Fórum Script Brasil
  • 0

[Ajuda Ruby] Alterar codigo de peso de arestas - Caixeiro Viajante&#33


babylon

Question

Opa e ai galera tudo joia?

Queria alterar o peso das arestas fixando um peso nelas sem ser random e sem usar coordenadas como o algoritmo esta usando, fiz umas alterações, amis não consegui fixar peso ao invez de coordenadas em Ruby, alguém daria um HELP:

City = Struct.new(:x, :y, :name)
Route = Struct.new(:cities, :distance)

CITIES = []

def add_city(x, y, name)
  CITIES << City.new(x, y, name)
end

def calculate_distance(from, to)
  Math.sqrt((to.x-from.x)**2 + (to.y-from.y)**2).to_i
end

def go_route(route, routes)
  if route.cities.length == CITIES.length
    route.distance += calculate_distance(route.cities[-1], route.cities[0])
    route.cities << route.cities[0]
    routes << route
    return
  end


  for city in CITIES - route.cities
    new_route = Route.new(route.cities + [city], route.distance + calculate_distance(route.cities.last, city))
    go_route(new_route, routes)
  end
end

def go(routes, start_city)
  route = Route.new([start_city], 0)
  go_route(route, routes)
  routes
end

#def r(n=10)
#  (rand*n).to_i
#end

#for name in ["Barba.", "Juiz F", "Belo H", "Lafai.", "Barroso"]
#  add_city(r, r, name)
#end

add_city(2, 4, "Barba.")
add_city(1, 3, "Juiz F")
add_city(6, 8, "Belo H")
add_city(2, 5, "Lafai")
add_city(2, 6, "Barroso")

best_routes = go([], CITIES[4]).sort_by(&:distance)[0...1]

best_routes.each_with_index do |route, i|
  puts "\n"*2
  puts " Distance: #{route.distance}"
  puts " Cities:"

  last_city = nil
  distance  = 0
  puts "  %10s | %10s " % [ "City", "Distancia"]
  route.cities.each do |city|
    distance_between_cities = (last_city.nil? ? 0 : calculate_distance(last_city, city))
    puts "  %10s |     %i " % [city.name, distance+=distance_between_cities]
    last_city = city
  end

end

Bom é isso falou e fuiz.

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152k
    • Total Posts
      651.6k
×
×
  • Create New...