2023 day 15 in F#

Real: 00:00:00.024, CPU: 00:00:00.020, GC gen0: 0, gen1: 0, gen2: 0
This commit is contained in:
aru 2023-12-19 15:38:43 +01:00
parent 4a0560482d
commit 76c20b36c5
2 changed files with 57 additions and 0 deletions

1
2023/data/15/example Normal file
View File

@ -0,0 +1 @@
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7

56
2023/fsharp/day15.fsx Normal file
View File

@ -0,0 +1,56 @@
#time
open System
open System.Text.RegularExpressions
let (|Regex|_|) pattern input =
let m = Regex.Match(input, pattern)
if m.Success then
Some(List.tail [ for g in m.Groups -> g.Value ])
else
None
type Lens = String * int
let steps (s: string) = s.Split [| ',' |]
let hash = Seq.fold (fun a b -> (17 * (a + (int) b)) % 256) 0
let part1 input = input |> Seq.sumBy hash
let rec replaceOrAppend (l: Lens list) (s, n) =
match l with
| [] -> [ (s, n) ]
| (c, _) :: rest when c = s -> (s, n) :: rest
| x :: xs -> x :: replaceOrAppend xs (s, n)
let part2 input =
let foldStep acc step =
match step with
| Regex @"([a-z]+)-" [ s ] ->
let idx = hash s
Array.updateAt idx (List.filter (fun (c, _) -> not (c = s)) (Array.get acc idx)) acc
| Regex @"([a-z]+)=([0-9]+)" (s :: n :: []) ->
let idx = hash s
Array.updateAt idx (replaceOrAppend (Array.get acc idx) (s, int n)) acc
| _ -> failwith "Unreachable"
let arr = Array.init 256 (fun _ -> List.empty)
let folded = Seq.fold foldStep arr input
folded
|> Seq.indexed
|> Seq.map (fun (i, entries) -> entries |> Seq.indexed |> Seq.map (fun (ii, (_, n)) -> (i + 1, ii + 1, n)))
|> Seq.concat
|> Seq.sumBy (fun (box, pos, foc) -> box * pos * foc)
let main f =
let s = f |> IO.File.ReadLines |> Seq.head |> steps
printfn "%A" (part1 s)
printfn "%A" (part2 s)
0
main fsi.CommandLineArgs.[1]