Rucksack Reorganization
Description: https://adventofcode.com/2022/day/3
open System.IO
open System
type Input() =
let mapToPriority (c: char) : int =
let cVal = (int) c
if cVal <= (int) 'Z' then
cVal - (int) 'A' + 1 + 26
else
cVal - (int) 'a' + 1
let computePart1 (line: string) : int =
let sorted =
line
|> Seq.toArray
|> Array.splitInto 2
|> Array.map Array.distinct
|> Array.sortBy (fun x -> x.Length)
sorted[0]
|> Array.filter (fun x -> Array.contains x sorted[1])
|> Array.fold (fun acc key -> acc + (mapToPriority (key))) 0
let computePart2 (l1: string, l2: string, l3: string) =
let sorted =
[| l1; l2; l3 |]
|> Array.map (Seq.distinct >> Seq.toArray)
|> Array.sortBy (fun x -> x.Length)
sorted[0]
|> Array.find (fun c -> (Array.contains c sorted[1]) && (Array.contains c sorted[2]))
|> mapToPriority
member _.Compute(part: int) =
use stream = new StreamReader "./input.txt"
let mutable sum = 0
let mutable endOfFile = false
while (not endOfFile) do
let line = stream.ReadLine()
if (line = null) then
endOfFile <- true
else if (part = 1) then
sum <- sum + computePart1 line
else
sum <- sum + computePart2 (line, stream.ReadLine(), stream.ReadLine())
sum
let input = Input()
let part = (Environment.GetCommandLineArgs()[1]) |> int
printfn "%d" (input.Compute(part))