Created
December 10, 2021 15:23
-
-
Save aaronjeline/898a8910a9ef6952caf7f5e38e2fc951 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(require threading racket/trace) | |
(define FILE "/tmp/input") | |
(define lines | |
(with-input-from-file | |
FILE | |
(λ () | |
(port->lines (current-input-port))))) | |
(define (delim->kind c) | |
(match c | |
[#\{ 'CURLY] | |
[#\} 'CURLY] | |
[#\( 'PAREN] | |
[#\) 'PAREN] | |
[#\[ 'BLOCK] | |
[#\] 'BLOCK] | |
[#\< 'ANGLE] | |
[#\> 'ANGLE])) | |
(define (delim->dir c) | |
(match c | |
[#\{ 'OPEN] | |
[#\} 'CLOSE] | |
[#\( 'OPEN] | |
[#\) 'CLOSE] | |
[#\[ 'OPEN] | |
[#\] 'CLOSE] | |
[#\< 'OPEN] | |
[#\> 'CLOSE])) | |
(define (fresh-state) | |
(box '())) | |
(define (push! state kind) | |
(set-box! state (cons kind (unbox state)))) | |
(define (pop! state kind) | |
(define top (car (unbox state))) | |
(set-box! state (cdr (unbox state))) | |
(when (not (equal? top kind)) | |
(raise kind))) | |
(define (update-state! state kind dir) | |
(match dir | |
['OPEN (push! state kind)] | |
['CLOSE (pop! state kind)])) | |
(define (process-line line) | |
(define score 0 ) | |
(define state (fresh-state)) | |
(for [(c (in-list (string->list line)))] | |
(update-state! state (delim->kind c) (delim->dir c))) | |
(define scores (map kind->score (unbox state))) | |
(for [(indv-score (in-list scores))] | |
(set! score (+ (* score 5) indv-score))) | |
score) | |
(define (kind->score e) | |
(match e | |
['PAREN 1] | |
['BLOCK 2] | |
['CURLY 3] | |
['ANGLE 4])) | |
(define scores | |
(filter | |
identity | |
(for/list [(line (in-list lines))] | |
(with-handlers | |
[(symbol? (const #f))] | |
(process-line line))))) | |
(set! scores (sort scores <)) | |
(define odd/c (and/c number? odd?)) | |
(define/contract (halfway-idx len) | |
(-> odd/c number?) | |
(/ (sub1 len) 2)) | |
(list-ref scores (halfway-idx (length scores))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment