-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.d
158 lines (133 loc) · 2.42 KB
/
part1.d
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import std.stdio;
import std.string : chomp;
import std.algorithm : min, max, count;
class Tape
{
static immutable long length = 512;
bool[] arr;
this(string str)
in (str.length == length)
{
arr.length = length;
foreach (i, c; str)
arr[i] = c == '#';
}
bool opIndex(size_t i) const
in (i < 512)
{
return arr[i];
}
}
struct Point
{
long x, y;
}
class Image
{
bool[Point] map; // true = 1, false = 0, not present = 0
bool infinity = false;
private this()
{
}
/// String ctor
this(Lines)(Lines lines)
{
long y;
foreach (line; lines)
{
long x;
foreach (c; line)
{
map[Point(x, y)] = c == '#';
x++;
}
y++;
}
}
bool opIndex(Point p) const
{
if (p in map)
return map[p];
else
return infinity;
}
bool opIndexAssign(bool value, Point p)
{
map[p] = value;
return value;
}
long countOnes() const
{
return map.byValue.count(true);
}
Point topLeft() const
{
Point result;
foreach (p; map.byKey)
{
result.x = min(result.x, p.x);
result.y = min(result.y, p.y);
}
return result;
}
Point bottomRight() const
{
Point result;
foreach (p; map.byKey)
{
result.x = max(result.x, p.x);
result.y = max(result.y, p.y);
}
return result;
}
void print() const
{
Point begin = topLeft;
Point end = bottomRight;
foreach (y; begin.y - 3 .. end.y + 4)
{
foreach (x; begin.x - 3 .. end.x + 4)
{
Point p = Point(x, y);
write(this[p] ? '#' : '.');
}
writeln;
}
}
long tapeIndex(Point p) const
{
long result;
foreach (y; [p.y - 1, p.y, p.y + 1])
foreach (x; [p.x - 1, p.x, p.x + 1])
{
result <<= 1;
result |= this[Point(x, y)];
}
return result;
}
Image enhanced(Tape tape) const
{
Image result = new Image;
if (tape[0])
result.infinity = true;
Point begin = topLeft;
Point end = bottomRight;
foreach (y; begin.y - 1 .. end.y + 2)
foreach (x; begin.x - 1 .. end.x + 2)
{
Point p = Point(x, y);
result[p] = tape[tapeIndex(p)];
}
return result;
}
}
void main()
{
Tape tape = new Tape(readln.chomp);
readln;
Image image = new Image(stdin.byLine);
image = image.enhanced(tape);
image = image.enhanced(tape);
image.print;
image.countOnes.writeln;
}