Skip to content

Instantly share code, notes, and snippets.

@ntreu14
Created December 8, 2019 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntreu14/28edb4ce0e87176f1b80473ddbb0b749 to your computer and use it in GitHub Desktop.
Save ntreu14/28edb4ce0e87176f1b80473ddbb0b749 to your computer and use it in GitHub Desktop.
Alternative Solution to Advent of Code 2019 Day. I felt since consequent are using IntCode programs, this solution is more extensible.
let puzzleInput =
[1;0;0;3;1;1;2;3;1;3;4;3;1;5;0;3;2;10;1;19;1;19;9;23;1;23;6;27;2;27;13;31;1;10;31;35;1;10;35;39;2;39;6;43;1;43;5;47;2;10;47;51;1;5;51;55;1;55;13;59;1;59;9;63;2;9;63;67;1;6;67;71;1;71;13;75;1;75;10;79;1;5;79;83;1;10;83;87;1;5;87;91;1;91;9;95;2;13;95;99;1;5;99;103;2;103;9;107;1;5;107;111;2;111;9;115;1;115;6;119;2;13;119;123;1;123;5;127;1;127;9;131;1;131;10;135;1;13;135;139;2;9;139;143;1;5;143;147;1;13;147;151;1;151;2;155;1;10;155;0;99;2;14;0;0]
|> List.mapi (fun i v -> (i, v))
|> Map.ofList
let getOpCodeAction : int -> (int -> int -> int) option = function
| 1 -> Some (+)
| 2 -> Some (*)
| _ -> None
let rec runInstructions ip program =
match Map.tryFind ip program with
Some opCode ->
match opCode with
| 99 -> Some program
| code ->
let v1 = Map.tryFind (ip + 1) program
let v1Pos = v1 |> Option.bind (fun v -> Map.tryFind v program)
let v2 = Map.tryFind (ip + 2) program
let v2Pos = v2 |> Option.bind (fun v -> Map.tryFind v program)
let v3Pos = Map.tryFind (ip + 3) program
let action = getOpCodeAction code
match action, v1Pos, v2Pos, v3Pos with
| Some a, Some _v1, Some v2', Some v3Pos' ->
let newValue = a _v1 v2'
runInstructions (ip + 4) (Map.add v3Pos' newValue program)
| _ -> None
| None -> Some program
let solve noun verb =
Map.add 1 noun
>> Map.add 2 verb
>> runInstructions 0
>> Option.bind (Map.tryFind 0)
printfn "Part 1: %A" <| solve 12 2 puzzleInput
//// Part 2
let formula (noun, verb) = 100 * noun + verb
[1..99] |> List.collect (fun i -> [1..99] |> List.map (fun j -> (i, j)))
|> List.choose (fun (noun, verb) ->
match solve noun verb puzzleInput with
| Some s when s = 19690720 -> Some <| formula (noun, verb)
| _ -> None
)
|> printfn "Part 2: %A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment