-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay5.fs
More file actions
63 lines (48 loc) · 1.85 KB
/
Day5.fs
File metadata and controls
63 lines (48 loc) · 1.85 KB
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
61
62
63
module Day5
open System.IO
type IngredientDatabase =
{ freshRanges: (int64 * int64) array
ingredientIds: int64 array }
module IngredientDatabase =
let isFresh (id: int64) (database: IngredientDatabase) =
database.freshRanges
|> Array.exists (fun (low, high) -> id >= low && id <= high)
let countFreshIngredients (database: IngredientDatabase) =
database.ingredientIds
|> Array.sumBy (fun id -> if isFresh id database then 1 else 0)
let countAllPossibleFreshIngredients (database: IngredientDatabase) =
let inputRanges = database.freshRanges
let mutable low, high = inputRanges[0]
let mutable count = 0L
for nl, nh in inputRanges[1..] do
if nl > high then
count <- count + high - low + 1L
low <- nl
high <- nh
else
high <- max high nh
count + high - low + 1L
let parse filename =
let split = filename |> File.ReadAllText |> _.Split("\n\n")
let ranges =
split[0].Trim().Split("\n")
|> Array.map _.Split("-")
|> Array.map (fun [| a; b |] -> (int64 a, int64 b))
let ids = split[1].Trim().Split("\n") |> Array.map int64
{ freshRanges = ranges |> Array.sort
ingredientIds = ids }
module Tests =
open Xunit
[<Theory>]
[<InlineData("Inputs/Day5/test.txt", 3)>]
[<InlineData("Inputs/Day5/input.txt", 623)>]
let ``Part 1: The number of fresh ingredient IDs`` (filename: string, expected: int) =
let result = filename |> parse |> IngredientDatabase.countFreshIngredients
Assert.Equal(expected, result)
[<Theory>]
[<InlineData("Inputs/Day5/test.txt", 14)>]
[<InlineData("Inputs/Day5/input.txt", 353507173555373L)>]
let ``Part 2: The total number of ingredient IDs considered fresh`` (filename: string, expected: int64) =
let result =
filename |> parse |> IngredientDatabase.countAllPossibleFreshIngredients
Assert.Equal(expected, result)