This repository has been archived by the owner on Nov 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle18.fs
60 lines (46 loc) · 1.6 KB
/
puzzle18.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// https://adventofcode.com/2020/day/18
//
#if !INTERACTIVE
module Puzzle18
#else
#load "common.fs"
#r "nuget:Farkle, Version=6.3.2"
#endif
open System.IO
open Farkle
open Farkle.Builder
open common
let input = readLines (Path.Combine(__SOURCE_DIRECTORY__, "puzzle18.txt"))
open Farkle.Builder.OperatorPrecedence
let number = Terminals.genericUnsigned<uint64> "Number"
let expression = nonterminal "Expression"
expression.SetProductions(
!@ number |> asIs,
!@ expression .>> "+" .>>. expression => (fun x1 x2 -> x1 + x2),
!@ expression .>> "*" .>>. expression => (fun x1 x2 -> x1 * x2),
!& "(" .>>. expression .>> ")" |> asIs
)
module Part1 =
let private opScope =
OperatorScope(
LeftAssociative("+", "-", "*", "/")
)
let private parser = DesigntimeFarkle.withOperatorScope opScope expression |> RuntimeFarkle.build
let answer =
input
|> Seq.map (RuntimeFarkle.parseString parser)
|> Seq.map (function | Ok value -> value | Error error -> failwith (error.ToString()))
|> Seq.sum
module Part2 =
let private opScope =
OperatorScope(
LeftAssociative("*", "/"),
LeftAssociative("+", "-")
)
let private parser = DesigntimeFarkle.withOperatorScope opScope expression |> RuntimeFarkle.build
let answer =
input
|> Seq.map (RuntimeFarkle.parseString parser)
|> Seq.map (function | Ok value -> value | Error error -> failwith (error.ToString()))
|> Seq.sum