Created
December 6, 2016 00:39
-
-
Save keithn/9332d1eddf603d5d12bd67be1d28263b to your computer and use it in GitHub Desktop.
Advent Of Code 2016 - Day 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Day5 | |
open System | |
open System.Security.Cryptography | |
open System.Text | |
let input = @"reyedfim" | |
let bytes (s:string) = Encoding.ASCII.GetBytes(s) | |
let md5 (data : byte array) : string = | |
use md5 = MD5.Create() | |
(StringBuilder(), md5.ComputeHash(data)) | |
||> Array.fold (fun sb b -> sb.Append(b.ToString("x2"))) | |
|> string | |
let rec decode (s:string) (n:int) acc = | |
if (Seq.length acc) = 8 then acc | |
else | |
let candidate = s + n.ToString() | |
let hash = bytes candidate |> md5 | |
if hash.StartsWith("00000") then decode s (n + 1) (acc @ [hash.Substring(5,1)]) | |
else decode s (n + 1) acc | |
let position c = | |
match c with | |
| "0" -> Some 0 | |
| "1" -> Some 1 | |
| "2" -> Some 2 | |
| "3" -> Some 3 | |
| "4" -> Some 4 | |
| "5" -> Some 5 | |
| "6" -> Some 6 | |
| "7" -> Some 7 | |
| _ -> None | |
let rec decode2' (s:string) (n:int) acc = | |
if (Seq.length acc) = 8 then acc | |
else | |
let candidate = s + n.ToString() | |
let hash = bytes candidate |> md5 | |
if hash.StartsWith("00000") then | |
let pos = position ( hash.Substring(5 , 1) ) | |
match pos with | |
| Some p -> | |
if (Seq.exists (fun t -> (fst t) = p) acc) then decode2' s (n + 1) acc | |
else decode2' s (n + 1) (acc @ [(p, hash.Substring(6,1))]) | |
| _ -> decode2' s (n + 1) acc | |
else decode2' s (n + 1) acc | |
let decode2 s = decode2' s 0 [] |> Seq.sort |> (Seq.map snd) |> String.Concat | |
let day5 = | |
printfn "\n\nDay 5\n" | |
printfn "Part 1: %A" (decode input 0 []) | |
printfn "Part 2: %A" (decode2 input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment