Last active
December 8, 2023 06:16
-
-
Save object/f507692942aed955244f27ebf632855a to your computer and use it in GitHub Desktop.
Advent of Code 2023, December 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#time "on" | |
open System | |
open System.IO | |
open System.Collections.Generic | |
let input = | |
File.ReadAllLines(__SOURCE_DIRECTORY__ + "/../data/input08.txt") | |
let parseLine (str: string) = | |
str.Substring(0, 3), str.Substring(7, 3), str.Substring(12, 3) | |
let instructions = input[0] |> Array.ofSeq | |
let points = Dictionary<string, string * string>() | |
input | |
|> Seq.toList | |
|> List.skip 2 | |
|> List.iter (fun str -> | |
let (x,y,z) = parseLine str | |
points.Add(x, (y,z))) | |
let rec play (instructions: char array) instrIndex currentPoint stopCondition count = | |
let leftPoint, rightPoint = points[currentPoint] | |
let direction = instructions[instrIndex] | |
let nextPoint = if direction = 'L' then leftPoint else rightPoint | |
if stopCondition nextPoint then | |
count + 1 | |
else | |
let instrIndex = if instrIndex = instructions.Length-1 then 0 else instrIndex + 1 | |
play instructions instrIndex nextPoint stopCondition (count + 1) | |
// Part One | |
play instructions 0 "AAA" (fun x -> x = "ZZZ") 0 | |
// Part Two | |
let rec gcd x y = if y = 0L then abs x else gcd y (x % y) | |
let lcm x y = x * y / (gcd x y) | |
points.Keys | |
|> Seq.filter (fun x -> x.EndsWith "A") | |
|> Seq.map (fun x -> play instructions 0 x (fun (x: string) -> x.EndsWith "Z") 0) | |
|> Seq.fold (fun acc elt -> lcm elt acc) 1L |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment