/* * File: tsp.kt * Purpose: Tests the naive O(n!) TSP algorithm. * Compilation: kotlinc tsp.kt * Execution: kotlin TspKt * Author: San Skulrattanakulchai */ fun tsp(dist: Array) { val pi = IntArray(dist.size) { it } var minDist = Int.MAX_VALUE fun swap(i: Int, j: Int) { val tmp = pi[i] pi[i] = pi[j] pi[j] = tmp } fun perm(i: Int) { val n = dist.size if (i == n-1) { minDist = kotlin.math.min(minDist, pi.sumBy { dist[pi[it]][pi[(it+1) % n]] }) } else for (j in i until n) { swap(i, j) perm(i+1) swap(i, j) } } perm(1) println("minimum tour length = $minDist") } fun main(args: Array) { val dist = arrayOf( intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), intArrayOf(9, 0, 8, 7, 6, 5, 4, 3, 10, 1, 2), intArrayOf(8, 7, 0, 6, 5, 4, 3, 2, 9, 10, 1), intArrayOf(7, 6, 5, 0, 4, 3, 2, 1, 8, 9, 10), intArrayOf(4, 3, 2, 1, 0, 10, 9, 8, 7, 6, 5), intArrayOf(10, 9, 8, 7, 6, 0, 5, 4, 3, 2, 1), intArrayOf(7, 8, 9, 10, 1, 2, 0, 3, 4, 5, 6), intArrayOf(5, 4, 3, 2, 1, 6, 7, 0, 8, 9, 10), intArrayOf(10, 9, 8, 7, 6, 5, 4, 3, 0, 2, 1), intArrayOf(1, 2, 4, 3, 6, 5, 8, 7, 10, 0, 9), intArrayOf(3, 2, 1, 6, 5, 4, 9, 8, 7, 10, 0) ) tsp(dist) }