1
1
# Iterated Local Search algorithm in the Ruby Programming Language
2
-
3
2
# The Clever Algorithms Project: http://www.CleverAlgorithms.com
4
3
# (c) Copyright 2010 Jason Brownlee. Some Rights Reserved.
5
4
# This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Australia License.
@@ -65,7 +64,7 @@ def perturbation(cities, best)
65
64
return candidate
66
65
end
67
66
68
- def search ( cities , max_iterations , max_no_improv )
67
+ def search ( cities , max_iterations , max_no_improv , output_format = "human" )
69
68
best = { }
70
69
best [ :vector ] = random_permutation ( cities )
71
70
best [ :cost ] = cost ( best [ :vector ] , cities )
@@ -74,7 +73,11 @@ def search(cities, max_iterations, max_no_improv)
74
73
candidate = perturbation ( cities , best )
75
74
candidate = local_search ( candidate , cities , max_no_improv )
76
75
best = candidate if candidate [ :cost ] < best [ :cost ]
77
- puts " > iteration #{ ( iter +1 ) } , best=#{ best [ :cost ] } "
76
+ if output_format == "csv" then
77
+ puts "#{ ( iter + 1 ) } ,#{ best [ :cost ] } "
78
+ else # The default
79
+ puts " > iteration #{ ( iter +1 ) } , best=#{ best [ :cost ] } "
80
+ end
78
81
end
79
82
return best
80
83
end
@@ -93,7 +96,17 @@ def search(cities, max_iterations, max_no_improv)
93
96
# algorithm configuration
94
97
max_iterations = 100
95
98
max_no_improv = 50
99
+
100
+ output_format = "human"
101
+ if $*. length >= 1 then
102
+ output_format = "csv"
103
+ end
104
+
96
105
# execute the algorithm
97
- best = search ( berlin52 , max_iterations , max_no_improv )
98
- puts "Done. Best Solution: c=#{ best [ :cost ] } , v=#{ best [ :vector ] . inspect } "
106
+ best = search ( berlin52 , max_iterations , max_no_improv , output_format )
107
+ if output_format == "csv" then
108
+ puts "#{ best [ :cost ] } ,#{ best [ :vector ] . join ( "," ) } "
109
+ else
110
+ puts "Done. Best Solution: c=#{ best [ :cost ] } , v=#{ best [ :vector ] . inspect } "
111
+ end
99
112
end
0 commit comments