From: Greg Burri <greg.burri@gmail.com>
Date: Sun, 2 Dec 2018 13:40:40 +0000 (+0100)
Subject: Day 1
X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=6bcb61d2e89e9748135fd5093d0f38a0be593a86;p=advent_of_code_2018.git

Day 1
---

diff --git a/Day01.fs b/Day01.fs
index ca6f6b2..5659b61 100644
--- a/Day01.fs
+++ b/Day01.fs
@@ -1,5 +1,23 @@
 module AdventOfCode2018.Day01
 
-let readDigit d = int d - int '0'
+open System
 
-let parseInput (str : string) : string = str
+
+let parseInput (str : string) : int[] =
+    str.Split ([| "\r\n"; "\r"; "\n" |], StringSplitOptions.RemoveEmptyEntries) |> Array.map int
+
+let finalFrequency : seq<int> -> int =
+    Seq.sum
+
+let firstDuplicate (changes : seq<int>) : int =
+    let repeatedChanges = seq { while true do yield! changes }
+    Seq.scan (
+        fun (_, sum, frequencies) change ->
+            let sum' = sum + change
+            if Set.contains sum' frequencies then
+                (true, sum', frequencies)
+            else
+                (false, sum', Set.add sum' frequencies)
+
+    ) (false, 0, Set.empty) repeatedChanges
+    |> Seq.pick (fun (duplicate, sum, _) -> if duplicate then Some sum else None)
diff --git a/Program.fs b/Program.fs
index 1f93628..b3c7fb0 100644
--- a/Program.fs
+++ b/Program.fs
@@ -4,8 +4,8 @@ open System
 open System.IO
 
 let day01 () =
-    let input = File.ReadAllText "Data/day01.input" |> Day01.parseInput
-    input
+    let changes = File.ReadAllText "Data/day01.input" |> Day01.parseInput
+    sprintf "part1 = %A, part2 = %A" (Day01.finalFrequency changes) (Day01.firstDuplicate changes)
 
 let days : (unit -> string) array =
     [|