-
Notifications
You must be signed in to change notification settings - Fork 0
/
11.pl
115 lines (104 loc) · 2.56 KB
/
11.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
:- use_module(library(charsio)).
:- use_module(library(clpz)).
:- use_module(library(dcgs)).
:- use_module(library(format)).
:- use_module(library(lists)).
:- use_module(library(pio)).
:- use_module(library(debug)).
:- use_module(library(tabling)).
% From The Power of Prolog, section Memoization
:- dynamic(memo_/1).
memo(Goal) :-
( memo_(Goal)
-> true
; once(Goal),
assertz(memo_(Goal))
).
%% Parses a number
number(X) --> number([], X).
number(X, Z) --> [C], { char_type(C, numeric) }, number([C|X], Z).
number(X, Z) --> { length(X, L), L #> 0, reverse(X, X1), number_chars(Z, X1) }.
input([]) --> "\n".
input([X|Xs]) --> " ", number(X), input(Xs).
input([X|Xs]) --> number(X), input(Xs).
blink_memo(0, _, 1).
blink_memo(N, 0, Xs) :-
N #> 0,
N1 #= N - 1,
memo(blink_memo(N1, 1, Xs)).
blink_memo(N, X, Xs) :-
N #> 0,
X #> 0,
number_chars(X, Xc),
length(Xc, L),
0 #= L mod 2,
LL #= L // 2,
length(X1, LL),
append(X1, X2, Xc),
N1 #= N - 1,
number_chars(XX, X1),
memo(blink_memo(N1, XX, A)),
number_chars(YY, X2),
memo(blink_memo(N1, YY, B)),
Xs #= A + B.
blink_memo(N, X, Xs) :-
N #> 0,
X #> 0,
number_chars(X, Xc),
length(Xc, L),
1 #= L mod 2,
* portray_clause(case_c(N, X)),
N1 #= N - 1,
Y #= X * 2024,
memo(blink_memo(N1, Y, Xs)).
solve_memo(N, F, Solution) :-
phrase_from_file(input(Xs), F),
maplist(blink_memo(N), Xs, Scores),
sum_list(Scores, Solution).
% This tabled version _should_ work but there is a Rust panic happening.
:- table blink_tabled/3.
blink_tabled(0, _, 1) :- !.
blink_tabled(N, 0, Xs) :-
N #> 0,
!,
N1 #= N - 1,
blink_tabled(N1, 1, Xs).
blink_tabled(N, X, Xs) :-
N #> 0,
X #> 0,
number_chars(X, Xc),
length(Xc, L),
(0 #= L mod 2),
!,
LL #= L // 2,
length(X1, LL),
append(X1, X2, Xc),
N1 #= N - 1,
number_chars(XX, X1),
number_chars(YY, X2),
blink_tabled(N1, XX, A),
blink_tabled(N1, YY, B),
Xs #= A + B.
blink_tabled(N, X, Xs) :-
N #> 0,
X #> 0,
number_chars(X, Xc),
length(Xc, L),
1 #= L mod 2,
N1 #= N - 1,
Y #= X * 2024,
blink_tabled(N1, Y, Xs).
solve_tabled(N, F, Solution) :-
phrase_from_file(input(Xs), F),
maplist(blink_tabled(N), Xs, Scores),
sum_list(Scores, Solution).
run :-
time(
(
solve_memo(25, "11.txt", X),
format("Task 1: ~w~n", [X]),
solve_memo(75, "11.txt", Y),
format("Task 1: ~w~n", [Y])
)
),
halt.