Lean/2024/01: Add solution

This commit is contained in:
Felix Bargfeldt 2025-01-13 20:28:45 +01:00
parent 37a9423fdc
commit 542bfa2db6
Signed by: Defelo
GPG key ID: 2A05272471204DD3
5 changed files with 65 additions and 5 deletions

32
Lean/2024/01.lean Normal file
View file

@ -0,0 +1,32 @@
def Input := List Int × List Int
def parse (input : String) : Input :=
input
|>.trim
|>.splitOn "\n"
|>.map (
fun line => line
|>.splitOn " "
|>.filter (not ∘ String.isEmpty)
|>.map String.toInt!
|> fun nums => (nums.head!, nums.getLast!)
)
|>.unzip
def part1 (input : Input) : Nat :=
let fst := input.fst.mergeSort (· ≤ ·)
let snd := input.snd.mergeSort (· ≤ ·)
fst
|>.zip snd
|>.map (fun (a, b) => a - b |>.natAbs)
|>.foldl Nat.add 0
def part2 (input : Input) : Int :=
input.fst
|>.map (fun a => a * (input.snd.count a))
|>.foldl Int.add 0
def main (args : List String) : IO Unit := do
let input ← parse <$> (System.FilePath.mk args[0]! |> IO.FS.readFile)
IO.println $ part1 input
IO.println $ part2 input

23
Lean/justfile Normal file
View file

@ -0,0 +1,23 @@
alias r := run
alias e := example
alias t := test
alias ty := test-year
alias ta := test-all
_default:
@just --list
run year day *args:
lean --run {{args}} {{year}}/{{day}}.lean ../.cache/{{year}}/{{trim_start_match(day, "0")}}
example year day ex:
lean --run {{year}}/{{day}}.lean ../examples/{{year}}/{{trim_start_match(day, "0")}}/{{ex}}
test year day:
@diff <(just run {{year}} {{day}}) <(cat ../.cache/{{year}}/{{trim_start_match(day, "0")}}.{1,2})
test-year year:
@set -e; for day in $(ls {{year}}); do just test {{year}} $(basename $day .lean); done
test-all:
@set -e; for year in *; do [[ -d $year ]] && [[ "$year" =~ ^[0-9]+$ ]] || continue; just test-year $year; done

File diff suppressed because one or more lines are too long

View file

@ -159,6 +159,9 @@
# Ruby
ruby
solargraph
# Lean
lean4
];
PYTHONPATH = ".";
LIBCLANG_PATH = with pkgs; lib.makeLibraryPath [llvmPackages.clang-unwrapped.lib];

View file

@ -14,6 +14,7 @@ names = {
"nix": "Nix",
"nu": "Nu",
"rb": "Ruby",
"lean": "Lean",
}
exts = {
"rs": [".rs"],
@ -24,13 +25,14 @@ exts = {
"nix": [".nix"],
"nu": [".nu"],
"rb": [".rb"],
"lean": [".lean"],
}
logos = {k.name.split(".")[0]: str(k) for k in Path(".assets").iterdir()}
def logo(lang, height=12):
return f'<img height={height} src="{logos[lang]}">'
return f'<img height={height} src="{logos[lang]}">' if lang in logos else ""
def link(year, day, lang):
@ -51,7 +53,7 @@ def link(year, day, lang):
else:
url = f"{names[lang]}/{year}/{day:02}{ext}"
return f' [{logo(lang)}]({url} "{names[lang]} solution for {year}/{day:02}")'
return f' [{logo(lang) or names[lang]}]({url} "{names[lang]} solution for {year}/{day:02}")'
return ""