Damus

Recent Notes

Wiggenstein profile picture
Day 1

I only spent a couple weeks learning lean last year, so there's probably a better way to do everything. (I know I could've used get! there, but I wanted to include a proof because it's just slightly modified haskell otherwise)

import Std.Data.HashMap

partial def readFile (f : IO.FS.Stream) (r : ByteArray) : IO ByteArray := do
let buf ← f.read 10000
if buf.isEmpty then
pure r
else
readFile f (r.append buf)

def getFileContents (f : System.FilePath) : IO (Except String String) := do
let file := IO.FS.Stream.ofHandle (← IO.FS.Handle.mk f IO.FS.Mode.read)
try
let contents ← readFile file ByteArray.empty
match contents.utf8Decode? with
| none => pure (Except.error "Not a text file")
| some l => pure (Except.ok (String.ofList l.toList))
catch e =>
pure (Except.error s!"I/O Exception {e}")


def processFile (f : System.FilePath) : IO (Except String (List Nat)) := do
if (← f.pathExists) then
match (← getFileContents f) with
| Except.error e => pure (Except.error e)
| Except.ok c =>
let notEmpty := λ (s : String) => not s.isEmpty
let words := (c.split (·.isWhitespace)).toStringList.filter notEmpty
let ids? := words.map String.toNat?
if h : ids?.idxOf? none = none then
have hallsome : ∀x ∈ ids?, x.isSome := by
have hnnone : ¬none ∈ ids? := by
rw [List.idxOf?_eq_none_iff] at h
exact h
intro x hx
cases x with
| none => exact absurd (hnnone hx) (by simp)
| some _ => trivial
let ids := ids?.attach.map fun (x : {y // y ∈ ids?}) =>
let id := x.val
let hid := x.property
id.get (hallsome id hid)
pure (Except.ok ids)
else
pure (Except.error "Wrong file format")
else
pure (Except.error "File not found")

def countIds (lst : List Nat) : List (Nat × Nat) :=
let rec countIds_intl : List Nat → Std.HashMap Nat Nat → Std.HashMap Nat Nat
| [], m => m
| x :: xs, m =>
match m.getKey? x with
| none => countIds_intl xs (m.insert x 1)
| some _ => countIds_intl xs (m.modify x (· + 1))
let map := countIds_intl lst Std.HashMap.emptyWithCapacity
let lst := map.toList
lst

def main (args : List String) : IO Unit :=
match args with
| f :: [] => do
match (← processFile f) with
| Except.error e => IO.println e
| Except.ok n =>
let ids := countIds n
if ids.length ≥ 3 then
let sids := ids.mergeSort λ x y => x.snd > y.snd -- replace > with < for part 2
let r := (sids.take 3).foldl (· * ·.fst) 1
IO.println r
else
IO.println "Not enough unique IDs"
| _ => IO.println "Exactly one input file required"
Wiggenstein profile picture
i kinda assumed that jonathan blow added talking characters to order of the sinking star at the behest of his publisher and didn't expect it to have an actual story
Wiggenstein profile picture
order of the sinking star is difficult to talk about without spoiling anything, so i’ll just say that this time the jon blow twist was not at all what i was expecting. it was the coolest thing i’ve seen in a video game in years, if not decades, but it was something only a puzzle game could pull off