summary refs log blame commit diff stats
path: root/day14.fsx
blob: 85d696f6827f776fb0c4c6e9573a3159190a4bc0 (plain) (tree)














































                                                                                                
open System
open System.IO

let revSublist nums pos n =
    let c = Array.copy nums
    for i in [0..n-1] do
        nums.[(pos + i) % 256] <- c.[(pos + n - i - 1) % 256]
    
let hash nRounds input =
    let nums = [|0..255|]
    let mutable pos = 0
    let mutable skipsize = 0

    for _ in [1..nRounds] do 
        for n in input do
            revSublist nums pos n
            pos <- pos + n + skipsize
            skipsize <- skipsize + 1
    nums

let hexHash (input: string) =
    input
    |> Seq.map (fun c -> byte c)
    |> (fun a -> Seq.append a [|17uy; 31uy; 73uy; 47uy; 23uy|])
    |> Seq.map int
    |> hash 64
    |> Array.chunkBySize 16
    |> Array.map (Array.reduce (^^^))
    |> Array.fold (fun str digit -> str + sprintf "%02x" digit) ""

let hashCount input =
    input
        |> Seq.countBy id 
        |> dict
        |> (fun x -> x['1'])

let hashString input index =
    sprintf "%s-%d" input index
        |> hexHash 
        |> Seq.map (fun x -> Convert.ToString(Convert.ToInt32(string x, 16), 2).PadLeft(4, '0'))
        |> String.concat ""

let () =
    let input = "amgozmfv"
    let hashes = [ for i in [0..127] do yield hashString input i ]
    File.WriteAllLines("day14regions.txt", hashes)
    List.map hashCount hashes |> List.sum |> printfn "%d"