Created
January 8, 2023 03:12
-
-
Save jtt9340/911f9b6bfe039728c9595b669cd17ec7 to your computer and use it in GitHub Desktop.
Advent of Code 2022 Day 3 in Clojure
This file contains 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
(ns aoc2022.day-3 | |
(:gen-class) | |
(:require [clojure.set :as set]) | |
(:import (java.lang Character) | |
(java.io BufferedReader))) | |
(defn letter->priority | |
"Get the priority of a letter" | |
[letter] | |
(let [ord (int letter)] | |
(- ord | |
(if (Character/isLowerCase ord) 96 38)))) | |
(defn priority | |
"Get the priority of the item in common in both compartments of a rucksack" | |
[rucksack] | |
(let [pivot (/ (count rucksack) 2) | |
fst-compartment (subs rucksack 0 pivot) | |
snd-compartment (subs rucksack pivot) | |
fst-compartment-set (into (sorted-set) (map letter->priority fst-compartment)) | |
snd-compartment-set (into (sorted-set) (map letter->priority snd-compartment))] | |
(last (set/intersection fst-compartment-set snd-compartment-set)))) | |
(defn priority-sum | |
"Gets the sum of the priorities for each rucksack" | |
[rucksacks] | |
(apply + (map priority rucksacks))) | |
(defn badge-priority-sum | |
"Gets the sum of the priorities for each badge in a group of three rucksacks" | |
([rucksacks] | |
(badge-priority-sum rucksacks 0)) | |
([rucksacks sum] | |
(if (empty? rucksacks) | |
sum | |
(let [item-type-priority (last (apply set/intersection | |
(for [grp (take 3 rucksacks) | |
:let [compartment-set (into (sorted-set) (map letter->priority grp))]] | |
compartment-set)))] | |
(recur (drop 3 rucksacks) (+ sum item-type-priority)))))) | |
(defn part-1 | |
[] | |
(with-open [stdin (BufferedReader. *in*)] | |
(println (priority-sum (line-seq stdin))))) | |
(defn part-2 | |
[] | |
(with-open [stdin (BufferedReader. *in*)] | |
(println (badge-priority-sum (line-seq stdin))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment