Class 40 — Wednesday, December 1

Chrestomathics

Let's go on a tour – Travel city to city – Then come back to home


Look both ways


Agenda



Computing grade


TSP recap

3 TSP tours
3 TSP tours

 


Task


Function d( cities, i1, i2 )

testing d()

cities: [(281, 468), (515, 643), (738, 88), (530, 120), (410, 754)]

a: 2

b: 4

d( cities, a, b ): 742.4



Function swap( tour, i1, i2 )

testing swap()

i1: 2

i2: 4

tour before swapping at indices i1 and i2: [4, 3, 1, 0, 2]

tour after swapping at indices i1 and i2: [4, 3, 2, 0, 1]



Function cost( cities, tour )

Set n to number of cities.

Initialize accumulator to 0.

For i in the inclusive interval 0 ... n-2 do

  Set a and b to be respectively the ith and i+1th tour entries.

  Add to the accumulator the distance between the ath and bth cities entries.

Set a and b to be respectively the 0th and n-1th tour entries.

Add to the accumulator the distance between the ath and bth cities entries.

testing cost()

cities: [(281, 468), (515, 643), (738, 88), (530, 120), (410, 754)]

tour: [4, 2, 0, 3, 1]

cost( cities, tour ): 2440.7