Skip to content

Instantly share code, notes, and snippets.

@object
Created December 1, 2023 08:38
Show Gist options
  • Select an option

  • Save object/b878ad34ceabfec7731c3b1f9eca75b1 to your computer and use it in GitHub Desktop.

Select an option

Save object/b878ad34ceabfec7731c3b1f9eca75b1 to your computer and use it in GitHub Desktop.
Advent of Code 2023, December 1
open System
open System.IO
let input =
File.ReadAllLines(__SOURCE_DIRECTORY__ + "/../data/input01.txt")
|> Seq.toList
let findNum1 x =
if x >= '0' && x <= '9' then Some (int (x-'0')) else None
let digits = ["one"; "two"; "three"; "four"; "five"; "six"; "seven"; "eight"; "nine"]
let rec findNum2 (str: string) (digits: string list) =
printfn "%s" str
if str[0] >= '0' && str[0] <= '9' then
int (str[0]-'0')
else
match digits |> List.tryFindIndex (fun x -> str.StartsWith x) with
| Some n -> n + 1
| None -> findNum2 (str.Substring(1)) digits
let reverseString (str: string) =
str |> Seq.toArray |> Array.rev |> String
// Part One
input
|> List.map (fun str -> str |> Seq.toList)
|> List.map (fun chars -> chars |> List.pick findNum1, chars |> List.rev |> List.pick findNum1)
|> List.map (fun (x,y) -> x * 10 + y)
|> List.sum
// Part Two
input
|> List.map (fun str -> findNum2 str digits, findNum2 (reverseString str) (digits |> List.map reverseString))
|> List.map (fun (x,y) -> x * 10 + y)
|> List.sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment