Skip to content

Instantly share code, notes, and snippets.

@jhusain
Last active December 7, 2024 19:20
Show Gist options
  • Save jhusain/b57d64f5c4e1a389ba7b065f3be03d06 to your computer and use it in GitHub Desktop.
Save jhusain/b57d64f5c4e1a389ba7b065f3be03d06 to your computer and use it in GitHub Desktop.
module Advent2024.Problem7
let file = """
190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20
"""
type Equation = Equation of (int * int list)
let showEquation (Equation (answer, numbers))=
sprintf
"Equation(%d,[%s])"
answer
(String.concat ", " (numbers |> Seq.map (fun num -> sprintf "%d" num)))
let parseNumbers (numbersString: string) =
numbersString.Trim().Split(" ")
|> Seq.map
(fun numberString ->
match System.Int32.TryParse(numberString) with
| (true, number) -> number
|_ -> failwith (sprintf "Expected %s to be Int32" numberString))
|> Seq.toList
let equations =
file.Trim().Split("\n")
|> Seq.map (
fun x->
match x.Split(":") with
| [| answerString; numbersString |] ->
match System.Int32.TryParse(answerString) with
| (true, answer) ->
Equation (answer, parseNumbers numbersString)
| (false, _) -> failwith "Expected answer to be Int32"
| _ -> failwith "Expected answer and numbers to be seperated by a single ':'"
)
let operations =
[
fun acc cur -> acc * cur;
fun acc cur -> acc + cur;
]
let rec getAnswersHelper (numbers: int list) (acc: int) =
match numbers with
| head :: tail ->
operations
|> Seq.collect (fun op ->
getAnswersHelper tail (op acc head)
)
| [] -> seq { yield acc }
let getAnswers (numbers: int list) =
match numbers with
| [value] -> seq {yield value}
| head :: tail -> getAnswersHelper tail head
| _ -> failwith "Each equation must contain at least one term"
let getSolvableEquations equations =
equations
|> Seq.filter (
fun (Equation (answer, numbers)) ->
getAnswers numbers
|> Seq.exists (fun result -> result = answer)
)
let output =
getSolvableEquations equations
|> Seq.map showEquation
|> String.concat ","
printf "Anser:%s" output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment