Day 8 part 2
This commit is contained in:
@@ -2,7 +2,6 @@ namespace AdventOfCode2023
|
||||
|
||||
open System
|
||||
open System.Collections.Generic
|
||||
open System.Globalization
|
||||
|
||||
[<RequireQualifiedAccess>]
|
||||
module Day8 =
|
||||
@@ -20,8 +19,9 @@ module Day8 =
|
||||
|
||||
lines.MoveNext () |> ignore
|
||||
|
||||
let stepsLine = lines.Current.TrimEnd()
|
||||
let stepsLine = lines.Current.TrimEnd ()
|
||||
let steps = Array.zeroCreate stepsLine.Length
|
||||
|
||||
for i = 0 to stepsLine.Length - 1 do
|
||||
steps.[i] <- (stepsLine.[i] = 'R')
|
||||
|
||||
@@ -49,19 +49,60 @@ module Day8 =
|
||||
let mutable i = 0
|
||||
let mutable currentNode = "AAA"
|
||||
let mutable answer = 0
|
||||
|
||||
while currentNode <> "ZZZ" do
|
||||
let instruction = data.Nodes.[currentNode]
|
||||
|
||||
if data.Steps.[i] then
|
||||
// "true" is R
|
||||
currentNode <- snd instruction
|
||||
else
|
||||
currentNode <- fst instruction
|
||||
|
||||
i <- (i + 1) % data.Steps.Length
|
||||
answer <- answer + 1
|
||||
|
||||
answer
|
||||
|
||||
let inline lcm (periods : ^T[]) =
|
||||
let mutable lcm = periods.[0]
|
||||
let mutable i = 1
|
||||
|
||||
while i < periods.Length do
|
||||
let euclid = Arithmetic.euclideanAlgorithm lcm periods.[i]
|
||||
lcm <- (lcm * periods.[i]) / euclid.Hcf
|
||||
i <- i + 1
|
||||
|
||||
lcm
|
||||
|
||||
let part2 (s : string) =
|
||||
let data = parse s
|
||||
let mutable answer = 0
|
||||
|
||||
answer
|
||||
let startingNodes =
|
||||
data.Nodes.Keys
|
||||
|> Seq.choose (fun k -> if k.[k.Length - 1] = 'A' then Some k else None)
|
||||
|> Seq.toArray
|
||||
|
||||
let periods =
|
||||
startingNodes
|
||||
|> Array.map (fun startNode ->
|
||||
let mutable i = 0
|
||||
let mutable currentNode = startNode
|
||||
let mutable answer = 0ul
|
||||
|
||||
while currentNode.[currentNode.Length - 1] <> 'Z' do
|
||||
let instruction = data.Nodes.[currentNode]
|
||||
|
||||
if data.Steps.[i] then
|
||||
// "true" is R
|
||||
currentNode <- snd instruction
|
||||
else
|
||||
currentNode <- fst instruction
|
||||
|
||||
i <- (i + 1) % data.Steps.Length
|
||||
answer <- answer + 1ul
|
||||
|
||||
uint64 answer
|
||||
)
|
||||
|
||||
lcm periods
|
||||
|
||||
Reference in New Issue
Block a user