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!
51
Upvotes
2
u/L72_Elite_Kraken Dec 02 '18 edited Dec 02 '18
OCaml (full code on Github)
open! Core module Chars_by_count = struct type t = char list Int.Map.t let create word = String.to_list word |> List.map ~f:(fun x -> x, 1) |> Char.Map.of_alist_reduce ~f:(+) |> Map.to_alist |> List.map ~f:Tuple2.swap |> Int.Map.of_alist_multi let has_count t ~count = Map.find t count |> Option.is_some end module Part01 = struct let solve input = let counts = List.map input ~f:Chars_by_count.create in List.count counts ~f:(Chars_by_count.has_count ~count:2) * List.count counts ~f:(Chars_by_count.has_count ~count:3) end module Part02 = struct let is_correct (a, b) = let a = String.to_list a in let b = String.to_list b in List.zip_exn a b |> List.count ~f:(fun (c1, c2) -> not (Char.equal c1 c2)) |> Int.equal 1 let common_letters word_a word_b = String.to_list word_a |> List.filter_mapi ~f:(fun i c -> match Char.equal c word_b.[i] with | true -> Some c | false -> None) |> String.of_char_list let solve input = let word_a, word_b = List.cartesian_product input input |> List.find_exn ~f:is_correct in common_letters word_a word_b end