-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.pl
46 lines (39 loc) · 1.45 KB
/
solution.pl
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
readFile(Path, Lines) :- open(Path, read, File), read_string(File, _, Str), split_string(Str, "\n", "\n", Lines).
main(R) :-
readFile("input", Input),
maplist(group, Input, Groups),
/*flatten(Groups, Programs),
connected(Programs, Groups, [0], Relations),
sort(Relations, Uniques),*/
connected([0], [], Groups, Uniques),
length(Uniques, R), !.
part2(R) :-
readFile("input", Input),
maplist(group, Input, Groups),
flatten(Groups, Programs),
supergroups(Programs, Groups, 0, R), !.
/*connected([], _, R, R).
connected([H|T], Groups, X, R) :-
member(H, X) -> connected(Groups, H, X1), connected(T, Groups, X1, R) ; connected(T, Groups, X, R).
connected([], R, R).
connected([H|T], X, R) :-
member(Y, H), member(Y, X) -> flatten([H|X], X1), connected(T, X1, R) ; connected(T, X, R).*/
connected([], _, _, []).
connected([H|T], Visited, Groups, [H|R]):-
select([H|Programs], Groups, NGroups),
subtract(Programs, [H|Visited], NPrograms),
union(T, NPrograms, NT),
connected(NT, [H|Visited], NGroups, R).
supergroups([], _, Ac, Ac) :- !.
supergroups([N|Nodes], Groups, Ac, R) :-
connected([N], [], Groups, Cs),
subtract(Nodes, Cs, NNodes),
NAc is Ac+1,
supergroups(NNodes, Groups, NAc, R).
group(Line, Result) :-
split_string(Line, "<->", " <-> ", [ A, B ]),
split_string(B, ", ", ", ", Bs),
maplist(toInt, Bs, BsInt),
toInt(A, AInt),
Result = [ AInt | BsInt ].
toInt(String, Int) :- atom_codes(String, Code), number_codes(Int, Code).