Simulated annealing: Difference between revisions

Updated to work with Nim 1.4: replaced several "rand" by "sample"; replaced "lc" by "toSeq".
(Added Wren)
(Updated to work with Nim 1.4: replaced several "rand" by "sample"; replaced "lc" by "toSeq".)
Line 741:
 
=={{header|Nim}}==
<lang Nim>import math, random, sugarsequtils, strformat
from times import cpuTime
 
const
Line 751 ⟶ 750:
case x
of 0:
randsample([1, 10, 11])
of 9:
randsample([8, 18, 19])
of 90:
randsample([80, 81, 91])
of 99:
randsample([88, 89, 98])
elif x > 0 and x < 9: # top ceiling
randsample [x-1, x+1, x+9, x+10, x+11]
elif x > 90 and x < 99: # bottom floor
randsample [x-11, x-10, x-9, x-1, x+1]
elif x mod 10 == 0: # left wall
randsample([x-10, x-9, x+1, x+10, x+11])
elif (x+1) mod 10 == 0: # right wall
randsample([x-11, x-10, x-1, x+9, x+10])
else: # center
randsample([x-11, x-10, x-9, x-1, x+1, x+9, x+10, x+11])
 
proc neighbor(s: seq[int]): seq[int] =
result = s
var city = rand sample(s)
var cityNeighbor = city.randomNeighbor
while cityNeighbor == 0 or city == 0:
city = rand sample(s)
cityNeighbor = city.randomNeighbor
result[s.find city].swap result[s.find cityNeighbor]
Line 802 ⟶ 801:
var
s = block:
var x = lc[x | toSeq(x <- 0 .. 99), int]
template shuffler: int = rand(1 .. x.len-1high)
for i in 1 .. x.len-1high:
x[i].swap x[shuffler()]
x
let startTime = cpuTime()
echo fmt"E(s0): {energy s:6.4f}"
for k in 0 .. kMax:
Line 824 ⟶ 822:
echo fmt"E(sFinal): {energy s:6.4f}"
echo fmt"path: {s}"
#echo fmt"ended after: {cpuTime() - startTime}"
 
main()</lang>
Line 831 ⟶ 828:
{{out}}
Sample run:
<pre>E(s0): 505.1591
E(s0): 505.1591
k: 0 T: 1.00 Es: 505.1591
k: 100000 T: 0.90 Es: 196.5216
Line 845 ⟶ 841:
k: 1000000 T: 0.00 Es: 103.3137
E(sFinal): 103.3137
path: @[0, 10, 11, 22, 21, 20, 30, 31, 41, 40, 50, 51, 61, 60, 70, 71, 81, 80, 90, 91, 92, 93, 82, 83, 73, 72, 62, 63, 53, 52, 42, 32, 33, 23, 13, 14, 24, 34, 35, 25, 15, 16, 26, 36, 47, 48, 38, 39, 49, 59, 58, 57, 68, 69, 79, 89, 99, 98, 97, 96, 95, 94, 84, 74, 75, 85, 86, 87, 88, 78, 77, 67, 76, 66, 65, 64, 54, 43, 44, 45, 55, 56, 46, 37, 27, 28, 29, 19, 9, 8, 18, 17, 7, 6, 5, 4, 3, 2, 12, 1, 0]</pre>
</pre>
 
=={{header|Perl}}==
Anonymous user