-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.fs
89 lines (66 loc) · 2.29 KB
/
Utils.fs
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
module AoC2021.Utils
open System
open System.Collections.Generic
open System.IO
open System.Text.RegularExpressions
let readLines filePath = File.ReadLines(filePath)
let readInput (s: string) = readLines (__SOURCE_DIRECTORY__ + (sprintf "/input/%s.txt" s))
let getProblem (a: seq<string>) : string = a |> Seq.head
module Seq =
let repeatForever s =
let c = Seq.cache s
seq {
while true do
yield! c
}
let filteri f =
Seq.mapi (fun i v -> (i, v))
>> Seq.filter (fun v -> f (fst v) (snd v))
>> Seq.map snd
let split (c: char) (s: string) = s.Split c
let splitS (sep: string) (s: string) = Regex.Split(s, sep)
let splitByLinefeed (s: string) = s.Split '\n'
let splitByTwoLinefeeds s = Regex.Split(s, "\n\n")
let readInputDelimByEmptyLine inputfile = readInput inputfile |> String.concat "\n" |> splitByTwoLinefeeds
let charToL (c: char) = int64 c - int64 '0'
let charToInt = charToL >> int
let hexToBits (value: seq<char>) =
value
|> Seq.map (fun n -> $"%04d{Convert.ToString(Convert.ToInt16(n.ToString(), 16), 2) |> int}")
|> String.concat ""
|> Seq.map (fun c -> int c - int '0')
let hexToBits2 value =
let raw =
Convert.ToString(Convert.ToInt64(value.ToString(), 16), 2)
|> Seq.map charToInt
match Seq.length raw % 8 with
| 6 -> Seq.append [ 0; 0 ] raw
| 0 -> raw
| _ -> failwith "Invalid input"
let bitsToInt bits =
let s = bits |> Seq.map string |> String.concat ""
Convert.ToInt64(s, 2)
let boolToSymbol falseC trueC =
function
| false -> falseC
| true -> trueC
let printImage boolToString (image: bool [] []) =
image
|> Array.iter (fun row -> (row |> Array.map boolToString |> String.concat "" |> printfn "%s"))
printfn ""
let rec cartesian inputs =
match inputs with
| h :: [] -> List.fold (fun acc elem -> [ elem ] :: acc) [] h
| h :: t ->
List.fold (fun cacc celem -> (List.fold (fun acc elem -> (elem :: celem) :: acc) [] h) @ cacc) [] (cartesian t)
| _ -> []
let memoize func =
let cache = Dictionary<_, _>();
fun key ->
let exists, value = cache.TryGetValue key
if exists then
value
else
let value = func key
cache.Add(key, value)
value