class GreedyRaAlgorithm::GreedyRaAlgorithm

Public Instance Methods

cost(shake, cities) click to toggle source

gets distance between two cities

# File lib/greedy_ra_algorithm.rb, line 11
def cost(shake, cities)
  distance = 0
  shake.each_with_index do |c1, i|
    c2 = (i == (shake.size - 1)) ? shake[0] : shake[i + 1]
    # +++ get distance between two cities
    distance += euc_2d cities[c1], cities[c2]
  end
  distance
end
euc_2d(c1, c2) click to toggle source

gets distance between cities

# File lib/greedy_ra_algorithm.rb, line 6
def euc_2d(c1, c2)
  Math.sqrt((c2[0] - c1[0]) ** 2.0 + (c2[1] - c1[1]) ** 2.0).round
end
randomized_greedy_solution(cities, greedy) click to toggle source

get solution

# File lib/greedy_ra_algorithm.rb, line 48
def randomized_greedy_solution(cities, greedy)
  candidate = {}
  candidate[:vector] = [rand(cities.size)]
  allCities = Array.new(cities.size){|i| i}
  while candidate[:vector].size < cities.size
    candidates = allCities - candidate[:vector]
    costs = Array.new(candidates.size) do |i|
      euc_2d(cities[candidate[:vector].last], cities[i])
    end
    rcl, max, min = [], costs.max, costs.min
    costs.each_with_index do |cost, i|
      rcl << candidates[i] if cost <= (min + greedy * (max - min))
    end
    candidate[:vector] << rcl[rand(rcl.size)]
  end
  candidate[:cost] = cost(candidate[:vector], cities)
  candidate
end
two_opt(shake) click to toggle source

gets reverse in range

# File lib/greedy_ra_algorithm.rb, line 22
def two_opt(shake)
  perm = Array.new(shake)
  c1, c2 = rand(perm.size), rand(perm.size)
  collection = [c1]
  collection << ((c1 == 0 ? perm.size - 1 : c1 - 1))
  collection << ((c1 == perm.size - 1) ? 0 : c1 + 1)
  c2 = rand(perm.size) while collection.include? (c2)
  c1, c2 = c2, c1 if c2 < c1
  # +++ reverses in range
  perm[c1...c2] = perm[c1...c2].reverse
  perm
end