aboutsummaryrefslogtreecommitdiff
path: root/aoc-2022-dotnet/Day01
diff options
context:
space:
mode:
authorTomasz Chojnacki <tomaszchojnacki2001@gmail.com>2022-12-02 18:43:39 +0100
committerTomasz Chojnacki <tomaszchojnacki2001@gmail.com>2022-12-02 18:43:39 +0100
commit9889c41f556eb134527909b7e0f29224786d33ec (patch)
tree8513d08b953d0c7eff6a8ef895317d36f4fd2991 /aoc-2022-dotnet/Day01
parent0705a262782338deb9639304a798429e8792f5ec (diff)
downloadgleam_aoc2020-9889c41f556eb134527909b7e0f29224786d33ec.tar.gz
gleam_aoc2020-9889c41f556eb134527909b7e0f29224786d33ec.zip
Upload first two days of year 2022
Diffstat (limited to 'aoc-2022-dotnet/Day01')
-rw-r--r--aoc-2022-dotnet/Day01/Day01.fsproj18
-rw-r--r--aoc-2022-dotnet/Day01/Program.fs37
2 files changed, 55 insertions, 0 deletions
diff --git a/aoc-2022-dotnet/Day01/Day01.fsproj b/aoc-2022-dotnet/Day01/Day01.fsproj
new file mode 100644
index 0000000..e337a41
--- /dev/null
+++ b/aoc-2022-dotnet/Day01/Day01.fsproj
@@ -0,0 +1,18 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net7.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <Content Include="test.txt">
+ <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+ </Content>
+ <Content Include="input.txt">
+ <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+ </Content>
+ <Compile Include="Program.fs" />
+ </ItemGroup>
+
+</Project>
diff --git a/aoc-2022-dotnet/Day01/Program.fs b/aoc-2022-dotnet/Day01/Program.fs
new file mode 100644
index 0000000..ecc35f1
--- /dev/null
+++ b/aoc-2022-dotnet/Day01/Program.fs
@@ -0,0 +1,37 @@
+open System.IO
+
+let parseLine = function "" -> None | l -> Some(int l)
+let readInput path = File.ReadLines path |> Seq.map parseLine
+
+let splitOnNone xs =
+ let (lastGroup, result) = Seq.fold (fun (groupAcc, resultAcc) x ->
+ match x with
+ | Some(value) -> (value :: groupAcc, resultAcc)
+ | None -> (List.empty, (List.rev groupAcc) :: resultAcc)) (List.empty, List.empty) xs
+ in List.rev (if List.isEmpty lastGroup then result else lastGroup :: result)
+
+let groupCalorySums data = data |> splitOnNone |> List.map List.sum
+
+let mostTotalCalories data = data |> groupCalorySums |> List.max
+
+let rec insert x xs =
+ match xs with
+ | [] -> [x]
+ | y::ys -> if x < y then x::y::ys else y::insert x ys
+
+let topN n data =
+ Seq.fold (fun acc elem ->
+ if List.length acc < n then insert elem acc
+ elif List.head acc < elem then insert elem (List.tail acc)
+ else acc
+ ) List.empty data
+
+let top3TotalCaloriesSum data = data |> groupCalorySums |> topN 3 |> List.sum
+
+let test = readInput "test.txt"
+assert (mostTotalCalories test = 24000)
+assert (top3TotalCaloriesSum test = 45000)
+
+let input = readInput "input.txt"
+printfn "%d" (mostTotalCalories input)
+printfn "%d" (top3TotalCaloriesSum input)