summary refs log tree commit diff stats
path: root/day4.fsx
blob: dd9916a61f6e616b755be84dfff6098743189691 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
open System.IO
open System.Text.RegularExpressions
open System

let lines = File.ReadLines "day4.txt" |> Seq.toList

let (|Regex|_|) pattern input = 
    let m = Regex.Match(input, pattern)
    if m.Success then Some(List.tail [for g in m.Groups -> g.Value])
    else None

let validChecksum (info: string * int * string) =
    let (name, idNum, checksum) = info
    let counts = 
        name 
        |> String.filter ((<>) '-') 
        |> Seq.toList 
        |> List.countBy id
        |> List.sortBy fst
        |> List.sortBy (snd >> fun x -> -x)
    let topFive = (List.map fst counts)[0..4] |> Seq.map string|> String.concat "" 
    if topFive = checksum then idNum else 0

let getInfo string = 
        match string with
        | Regex "([a-z\-]*)-(\d+)\[([a-z]{5})\]" [name; id; checksum] -> 
            (name, int id, checksum)
        | _ -> ("", 0, "")

let totalChecksum =
    List.map (getInfo >> validChecksum) >> List.sum

// part 1
totalChecksum lines |> printfn "%A"

// part 2
let decrypt (offset: int) (letter: char) : string =
        match letter with
        | '-' -> " "
        | _ ->
            int letter 
            |> fun x -> x - (int 'a') + offset 
            |> fun x -> x % 26 
            |> ((+) (int 'a')) 
            |> Convert.ToChar
            |> string

let decryptValid (info: string * int * string) = 
    let (name, idNum, checksum) = info
    Seq.toList name |> List.map (decrypt idNum) |> String.concat "", idNum


let decrypted =
    List.map (getInfo >> decryptValid) >> List.filter (fst >> fun x -> x.Contains "north")

decrypted lines |> printfn "%A"