summary refs log tree commit diff stats
path: root/day5.fsx
blob: 2f7b4bad12dee511bda2c542f023304ee9fc9aee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
open System.Security.Cryptography
open System.Text

let input = "reyedfim"

let md5 (data: string): string = 
    use md5 = MD5.Create()
    (StringBuilder (), md5.ComputeHash(Encoding.ASCII.GetBytes data))
    ||> Array.fold (fun sb b -> sb.Append(b.ToString("x2")))
    |> string

let rec getPassword (count: int) (chars: string): string =
    if String.length chars = 8 then chars
    else
        let hashed = md5 (input + string count)
        if hashed[0..4] = "00000" then 
            getPassword (count + 1) (chars + string hashed[5])
        else
            getPassword (count + 1) chars

// part 1
getPassword 0 "" |> printfn "%s"

// part 2
let updateElement index newValue =
    String.mapi (fun i v -> if i = index then newValue else v)

let rec getPassword2 (count: int) (chars: string): string =
    if Seq.fold (fun x y -> x && (y <> ' ')) true chars then chars
    else
        let hashed = md5 (input + string count)
        if hashed[0..4] = "00000" then 
            let index = int hashed[5] - int '0'
            if index < 0 || index > 7 || chars[index] <> ' ' then
                getPassword2 (count + 1) chars
            else
                let newChar = hashed[6]
                let newChars = chars |> updateElement index newChar
                getPassword2 (count + 1) newChars
        else
            getPassword2 (count + 1) chars

getPassword2 0 "        " |> printfn "%s"