Skip to content

Instantly share code, notes, and snippets.

@alexander-yakushev
Last active December 7, 2023 08:04
Show Gist options
  • Save alexander-yakushev/ff300602825af2d639276df3c456d457 to your computer and use it in GitHub Desktop.
Save alexander-yakushev/ff300602825af2d639276df3c456d457 to your computer and use it in GitHub Desktop.
Advent of Code 2023, day 7
(ns day7
(:require [clojure.string :as str]
[clojure.java.io :as io]))
(def lines (vec (line-seq (io/reader "day7.txt"))))
(defn parse [task]
(for [line lines]
(let [[hand bid] (str/split line #" " )]
[(mapv #(case %
\J (case task
1 11
2 1)
\T 10, \Q 12, \K 13, \A 14
(parse-long (str %))) hand)
(parse-long bid)])))
(defn sorted-freqs [hand special-joker?]
(let [freqs (frequencies hand)]
(if special-joker?
;; J is 1
(update (vec (sort > (vals (dissoc freqs 1))))
0 (fnil + 0) (freqs 1 0))
(sort > (vals freqs)))))
(defn hands-comparator [special-joker?]
(fn [hand1 hand2]
(let [freq1 (sorted-freqs hand1 special-joker?)
freq2 (sorted-freqs hand2 special-joker?)
type (fn [[a b c d e]]
(cond (= a 5) 6
(= a 4) 5
(= [a b] [3 2]) 4
(= a 3) 3
(= a b 2) 2
(= a 2) 1
:else 0))
type1 (type freq1)
type2 (type freq2)]
(cond (< type1 type2) -1
(> type1 type2) 1
:else (compare hand1 hand2)))))
(defn solve [task]
(->> (parse task)
(sort-by first (hands-comparator (= task 2)))
(map-indexed (fn [i [_ bid]]
(* (inc i) bid)))
(reduce +)))
#_(solve 1)
#_(solve 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment