I sped through the 5hr F# pluralsight course this week-end and thought I'd sement my learning by going through as many Advent of Code puzzles I could with this new learning. However, already on day 2 I'm starting to question whether I'm too biased from C syntax and imperative coding to do it "right".
I really really miss being able to break from for loops for the second solution here. Sure I could make a
while loop and have a mutable
j, but it seems wrong either way. Also, I'd like function pointers for the "ops", but that's just a matter of doing some more work I guess.
In any case, some pointers on things to improve and make more declarative in the code would be super appreciated. Would really like to get going on the right foot before running off to day 3.
open System open System.IO let parse = fun (x:String) -> x.Split ',' |> Array.map int let run (ops:int) = let mutable i = 0 while i < ops.Length do match ops.[i] with | 1 -> let a = ops.[ops.[i+1]] let b = ops.[ops.[i+2]] ops.[ops.[i+3]] <- a + b i <- i + 4 | 2 -> let a = ops.[ops.[i+1]] let b = ops.[ops.[i+2]] ops.[ops.[i+3]] <- a * b i <- i + 4 | 99 -> i <- ops.Length | _ -> printfn "doh %A" i ops let test = parse >> run let test1 = test "1,0,0,0,99" let test2 = test "2,3,0,3,99" let test3 = test "2,4,4,5,99,0" let test4 = test "1,1,1,4,99,5,6,0,99" let input = parse <| File.ReadAllText (Path.Combine [|__SOURCE_DIRECTORY__;@"input.txt"|]) let prog1 = Array.copy input prog1.[1..2] <- [|12;2|] run prog1 |> ignore let exp = 19690720 let mutable solNounVerb = (0, 0) for i = 0 to 100 do for j = 0 to 100 do let prg = Array.copy input prg.[1..2] <- [|i;j|] run prg |> ignore if prg. = exp then solNounVerb <- (i, j) let sol2 = (fun (i, j) -> i * 100 + j) solNounVerb