Skip to content

Instantly share code, notes, and snippets.

@erasmas
Created December 3, 2019 17:14
Show Gist options
  • Save erasmas/978c608c39c317f6c2056b9ffa5d7a06 to your computer and use it in GitHub Desktop.
Save erasmas/978c608c39c317f6c2056b9ffa5d7a06 to your computer and use it in GitHub Desktop.
open System.IO
type Opcode = int
type InstructionPointer = int
type Noun = int
type Verb = int
type Program = int []
type Output = int
let input =
File.ReadAllText("./2019/data/day2.txt")
|> (fun (line: string) -> line.Split [| ',' |])
|> Seq.map int
|> Seq.toArray
let getValue (n: int) (arr: int []) =
Array.get arr (Array.get arr n)
let applyOp (arr: int []) (n: int) : int [] =
let f = match Array.get arr n with
| 1 -> (+)
| 2 -> (*)
| x -> failwithf "Unsupported operation: %d" x
let val1 = getValue (n + 1) arr
let val2 = getValue (n + 2) arr
let target = arr.[n + 3]
arr.[target] <- f val1 val2
arr
let compute (input: int []) (noun: Noun) (verb: Verb) =
let rec inner (currentPos: int) (arr: int []) =
match arr.[currentPos] with
| 99 -> arr
| n -> inner (currentPos + 4) (applyOp arr currentPos)
input.[1] <- noun
input.[2] <- verb
inner 0 (Array.copy input)
let findInputsForOutput (program: Program) (out: Output): (Noun * Verb) =
let result =
seq {
for noun in [0..99] do
for verb in [0..99] do
let result = compute program noun verb
if result.[0] = out
then yield noun, verb
}
Seq.head result
// part 2
let answer =
let (noun, verb) = findInputsForOutput input 19690720
100 * noun + verb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment