|(require aoc-racket/day09)||package: aoc-racket|
This puzzle is a version of the famous traveling-salesman problem. The problem is famous because there’s no reasonable algorithm to solve it for arbitrarily large sets of cities. This version, however, has only eight cities. So it is possible (and easiest) to simply try all the options and see which is shortest.
The solution has two parts. First, we’ll parse our input data and put the distances into a mutable hash table. One small wrinkle — the distance between city A and city B is the same whether our path takes us from A to B or B to A. So the keys for our hash will be of the form (list city-a city-b), with the cities always in alphabetical order.
In the second part, we’ll loop through every possible path between the cities with in-permutations. We’ll split each path into pairs of cities, look up each distance between pairs, and sum them. This will give us a list of distances, and we can find the smallest with min.
The reason the traveling-saleman problem is generally difficult is that the number of permutations of n cities is (factorial (sub1 n)), which gets very large, very quickly.
(require racket rackunit) (provide (all-defined-out)) (define distances (make-hash)) (define (str->hash ln) (match-define (list _ here there dist) (regexp-match #px"^(\\w+) to (\\w+) = (\\d+)" ln)) (define key (places->key here there)) (hash-set! distances key (string->number dist))) (define (places->key here there) (sort (list (string-downcase here) (string-downcase there)) string<?)) (define (calculate-route-distances) (define (pairify xs) (map list (drop-right xs 1) (drop xs 1))) (define (distance here there) (hash-ref distances (places->key here there) +inf.0)) (define cities (remove-duplicates (append* (hash-keys distances)))) (for/list ([route (in-permutations cities)]) (for/sum ([pair (in-list (pairify route))]) (apply distance pair))))