Created
December 18, 2020 10:27
-
-
Save Karamell/19e58c8e33fdd7bd694a3bbcb5c3f8dc to your computer and use it in GitHub Desktop.
Advent of Code 2020 day 18 in F#
This file contains hidden or 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
| #time "on" | |
| let lines = System.IO.File.ReadAllLines ( __SOURCE_DIRECTORY__ + "/input.txt") | |
| let parseLine l = l |> Seq.map id |> Seq.toList |> List.filter (fun c -> c <> ' ') | |
| let calc1 line = | |
| let rec calc (acc:int64) op = function | |
| | [] -> acc, [] | |
| | '+'::t -> calc acc (+) t | |
| | '*'::t -> calc acc ( * ) t | |
| | '('::t -> | |
| let (r, rt) = calc 0L (+) t | |
| let acc' = op r acc | |
| calc acc' op rt | |
| | ')'::t -> acc, t | |
| | n::t -> | |
| let acc' = op acc (n |> string |> int64) | |
| calc acc' op t | |
| parseLine line |> calc 0L (+) | |
| let calc2 line = | |
| let rec calc (acc:int64) op (multing:bool) = function | |
| | [] -> acc, [] | |
| | '+'::t -> calc acc (+) multing t | |
| | '*'::t when not multing -> | |
| let (r, rt) = calc 0L (+) true t | |
| let acc' = r * acc | |
| calc acc' op false rt | |
| | '*'::t when multing -> acc, '*' :: t | |
| | '('::t -> | |
| let (r, rt) = calc 0L (+) false t | |
| let acc' = op r acc | |
| calc acc' op multing rt | |
| | ')'::t -> acc, t | |
| | n::t -> | |
| let acc' = op acc (n |> string |> int64) | |
| calc acc' op multing t | |
| parseLine line |> calc 0L (+) false | |
| lines |> Array.map calc1 |> Array.map fst |> Array.sum |> printfn "Part 1: %d" | |
| lines |> Array.map calc2 |> Array.map fst |> Array.sum |> printfn "Part 2: %d" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment