From eedf2c63917a75c15e55f7c051c21722583dc19b Mon Sep 17 00:00:00 2001 From: Jonathan Chan Date: Wed, 25 Dec 2019 13:52:41 -0800 Subject: [PATCH] Day 18: Refactored for convenience for part 2, which I will do later. --- src/18.rkt | 64 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 54 insertions(+), 10 deletions(-) diff --git a/src/18.rkt b/src/18.rkt index a9dca78..fdfa928 100644 --- a/src/18.rkt +++ b/src/18.rkt @@ -3,10 +3,11 @@ (require racket/set data/heap graph + (only-in 2htdp/batch-io read-lines) (except-in "../lib.rkt" transpose)) (define input - (problem-input 18)) + (read-lines "../input/18.txt")) (define list-grid (map string->list input)) @@ -20,11 +21,21 @@ (define height (length list-grid)) -;; start : (coord . char) -;; coord = (list number number) -(define start - (cons #\@ (list (round (/ width 2)) - (round (/ height 2))))) +(define (show-grid) + (for-each displayln + (map (λ (s) + (string-replace (string-replace s "#" "█") "." " ")) + input))) + +;; keys : (setof char) +(define keys + (list->set + (cons #\@ + (map integer->char + (range (char->integer #\a) + (add1 (char->integer #\z))))))) + +;; coord : (list number number) ;; get-char : coord -> char (define (get-char coord) @@ -78,6 +89,17 @@ hash))) hash coords))) +;; start : (char . coord) +;; Char-coord pair of #\@, for convenience +(define start + (cons #\@ (hash-ref keys-hash #\@))) + +;; visited : (setof char) +;; Assume that we already have any key that does not +;; show up in the hash, as well as the starting point #\@ +(define visited + (set-add (set-subtract keys (list->set (hash-keys keys-hash))) #\@)) + ;; inter-keys-hash : (hashof (char => char)) ;; A hashmap from keys to the keys that must be collected ;; when taking the shortest path from #\@ to that key @@ -130,6 +152,25 @@ (not (set-member? visited key)) (andmap (∂ set-member? visited) (hash-ref doors-hash key))))) +;; We do a breadth-first search over an implicit graph. +;; The nodes of this graph are visit states, which consist of +;; the current key we are at, as well as the keys we have visited. +;; This is why state=? only compares key and visited when removing +;; states from the heap. +;; States are ordered by the total number of steps taken, +;; which is also saved in the state struct. +;; This is why state