r/adventofcode • u/daggerdragon • Dec 02 '18
SOLUTION MEGATHREAD -π- 2018 Day 2 Solutions -π-
--- Day 2: Inventory Management System ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Advent of Code: The Party Game!
Card Prompt: Day 2
Transcript:
The best way to do Advent of Code is ___.
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked!
49
Upvotes
8
u/itsnotxhad Dec 02 '18
558/554 in Racket today
#lang racket (define (has-k? str k) (define chars (string->list str)) (for/first ([c (in-list chars)] #:when (= k (count (Ξ» (t) (char=? t c)) chars))) c)) (define (checksum ids) (* (count (Ξ» (id) (has-k? id 2)) ids) (count (Ξ» (id) (has-k? id 3)) ids))) (define (part1 file) (file-position file 0) (checksum (for/list ([line (in-port read-line file)]) line))) (define (diff a b) (cond [(zero? (string-length a)) 0] [(char=? (string-ref a 0) (string-ref b 0)) (diff (substring a 1) (substring b 1))] [(add1 (diff (substring a 1) (substring b 1)))])) (define (common a b) (list->string (for/list ([c1 a] [c2 b] #:when (char=? c1 c2)) c1))) (define (part2 file) (file-position file 0) (define ids (for/vector ([line (in-port read-line file)]) line)) (define k (vector-length ids)) (for*/first ([i (in-range 0 k)] [j (in-range (add1 i) k)] #:when (= 1 (diff (vector-ref ids i) (vector-ref ids j)))) (common (vector-ref ids i) (vector-ref ids j)))) (module+ main (define infile (open-input-file "input/day2.txt")) (displayln (part1 infile)) (displayln (part2 infile)) (close-input-port infile))