You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
aoc-racket/2017/d3/main.rkt

50 lines
1.6 KiB
Racket

7 years ago
#lang sugar/debug br/quicklang
(require "../helper.rkt" sugar/cache)
(provide read-syntax)
(define (read-syntax path port)
(strip-context #`(module mod "main.rkt"
#,@(for/list ([datums (in-port read port)])
7 years ago
datums))))
7 years ago
(provide (rename-out [#%mb #%module-begin]))
(define-macro (#%mb STARS NUMBER ...)
#'(#%module-begin ((if (eq? 'STARS ') dist larger-sum) NUMBER) ...))
(define (ring-side r) (* 2 r))
(define (ring-last r) (expt (add1 (ring-side r)) 2))
(define (ring-first r) (if (zero? r) 1 (add1 (ring-last (sub1 r)))))
(define (ring int)
(for/first ([i (in-naturals)]
#:when (<= int (ring-last i)))
7 years ago
i))
7 years ago
(define (nth-coordinate n)
(cond
[(= n 1) 0]
[else
(define ring-idx (ring n))
(define offset (- n (ring-first ring-idx)))
(define-values (quadrant pos)
(quotient/remainder offset (ring-side ring-idx)))
(* (+ ring-idx (* +i (- pos (sub1 ring-idx)))) (expt +i quadrant))]))
(define (dist n)
(define c (nth-coordinate n))
(+ (abs (real-part c)) (abs (imag-part c))))
(define vals (make-hash))
(define (neighbor-sum n)
(define c (nth-coordinate n))
(hash-ref! vals c (λ () (if (= c 0)
1
7 years ago
(for*/sum ([h (in-list '(-1 0 1))]
[v (in-list '(-1 0 1))])
(define neighbor (+ h (* +i v)))
(hash-ref vals (+ c neighbor) 0))))))
7 years ago
(define (larger-sum x)
(for*/first ([n (in-naturals 1)]
#:when (> (neighbor-sum n) x))
7 years ago
(neighbor-sum n)))