-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.fsx
60 lines (46 loc) · 1.65 KB
/
main.fsx
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
let equationsPossible (equations: string list) : bool =
let rec createGraph (equations: string list) (graph: Set<int> []) =
match equations with
| [] -> graph
| h :: t ->
if h.[1] = '=' then
let a = int h.[0] - int 'a'
let b = int h.[3] - int 'a'
graph.[a] <- Set.add b graph.[a]
graph.[b] <- Set.add a graph.[b]
createGraph t graph
else
createGraph t graph
let rec colorGraph node color (graph: Set<int> []) (colors: int []) =
if colors.[node] <> -1 then
colors
else
colors.[node] <- color
graph.[node]
|> Set.fold (fun acc next -> colorGraph next color graph acc) colors
let rec equationsPossible' (equations: string list) (colors: int []) =
match equations with
| [] -> true
| h :: t ->
if h.[1] = '!' then
let a = int h.[0] - int 'a'
let b = int h.[3] - int 'a'
if colors.[a] = colors.[b] then
false
else
equationsPossible' t colors
else
equationsPossible' t colors
let graph = createGraph equations (Array.init 26 (fun _ -> Set.empty))
let colors =
seq { 0..25 }
|> Seq.fold (fun acc i -> colorGraph i i graph acc) (Array.zeroCreate 26)
equationsPossible' equations colors
// false
equationsPossible [ "a==b"; "b!=a" ]
// true
equationsPossible [ "a==b"; "b==a" ]
// false
equationsPossible [ "a==b"
"b!=c"
"c==a" ]