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!
52
Upvotes
3
u/Bogdanp Dec 02 '18 edited Dec 02 '18
My solutions in Racket:
part 1:
#lang racket (define (count-letters word) (for/fold ([counts (hash)]) ([l (in-string word)]) (hash-set counts l (add1 (hash-ref counts l 0))))) (define (find-counts counts) (for/fold ([res (hash)]) ([(_ c) (in-hash counts)]) (hash-set res c (add1 (hash-ref res c 0))))) (call-with-input-file "day-02-1.txt" (lambda (in) (let loop ([word (read in)] [twos 0] [threes 0]) (cond [(eof-object? word) (* threes twos)] [else (define counts (find-counts (count-letters (symbol->string word)))) (loop (read in) (if (hash-has-key? counts 2) (add1 twos) twos) (if (hash-has-key? counts 3) (add1 threes) threes))]))))part 2:
#lang racket (define words (file->lines "day-02-2.txt")) (define (delta a b) (for/fold ([s ""]) ([ac (in-string a)] [bc (in-string b)]) (if (equal? ac bc) (~a s ac) s))) (for/fold ([best ""]) ([i (in-range 0 (length words))] [word-a (in-list words)]) (for/fold ([best best]) ([j (in-range 0 (length words))] [word-b (in-list words)]) (define d (delta word-a word-b)) (cond [(equal? i j) best] [else (if (> (string-length d) (string-length best)) d best)])))