class TabooSearch::TabooSearch

Public Instance Methods

candidate(best, taboo_list, cities) click to toggle source

candidate

# File lib/taboo_search.rb, line 57
def candidate(best, taboo_list, cities)
  shake, edges = nil, nil
  begin
    shake, edges = two_opt(best[:vector])
  end while is_taboo?(shake, taboo_list)
  candidate = {:vector => shake}
  candidate[:cost] = cost(candidate[:vector], cities)
  return candidate, edges
end
cost(shake, cities) click to toggle source

gets distance between two cities

# File lib/taboo_search.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/taboo_search.rb, line 6
def euc_2d(c1, c2)
  Math.sqrt((c2[0] - c1[0]) ** 2.0 + (c2[1] - c1[1]) ** 2.0).round
end
is_taboo?(shake, taboo_list) click to toggle source

is taboo

# File lib/taboo_search.rb, line 46
def is_taboo?(shake, taboo_list)
  shake.each_with_index do |c1, i|
    c2 = (i == (shake.size - 1)) ? shake[0] : shake[i + 1]
    taboo_list.each do |forbidden_edge|
      return true if forbidden_edge == [c1, c2]
    end
  end
  false
end
shake(cities) click to toggle source

shake

# File lib/taboo_search.rb, line 22
def shake(cities)
  shake = Array.new(cities.size){|i| i}
  shake.each_index do |i|
    r = rand(shake.size - 1) + 1
    shake[i], shake[r] = shake[r], shake[i]
  end
  shake
end
two_opt(shake) click to toggle source

gets reverse in range

# File lib/taboo_search.rb, line 32
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
  return perm, [[shake[c1 - 1], shake[c1]], [shake[c2 - 1], shake[c2]]]
end