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
|
const std = @import("std");
const print = std.debug.print;
pub fn solve(part: []u8, reader: *std.Io.Reader, allocator: std.mem.Allocator) !void {
if (std.mem.eql(u8, part, "1")) {
try part1(reader, allocator);
} else {
try part2(reader, allocator);
}
}
fn part1(reader: *std.Io.Reader, allocator: std.mem.Allocator) !void {
var output: usize = 0;
var list = try std.ArrayList([]u8).initCapacity(allocator, 0);
defer list.deinit(allocator);
while (reader.takeDelimiter('\n')) |line| {
if (line == null){
break;
}
try list.append(allocator, line.?);
} else |_| {
}
for (list.items,0..) |row, y| {
for (row,0..) |item,x| {
if (item != '@'){
continue;
}
var adjacent: usize = 0;
if (y > 0 and x > 0 and list.items[y - 1][x - 1] == '@') adjacent += 1;
if (y > 0 and list.items[y - 1][x] == '@') adjacent += 1;
if (y > 0 and x < row.len - 1 and list.items[y - 1][x + 1] == '@') adjacent += 1;
if (x > 0 and list.items[y][x - 1] == '@') adjacent += 1;
if (x < row.len - 1 and list.items[y][x + 1] == '@') adjacent += 1;
if (y < list.items.len - 1 and x > 0 and list.items[y + 1][x - 1] == '@') adjacent += 1;
if (y < list.items.len - 1 and list.items[y + 1][x] == '@') adjacent += 1;
if (y < list.items.len - 1 and x < row.len - 1 and list.items[y + 1][x + 1] == '@') adjacent += 1;
if (adjacent < 4){
output += 1;
}
}
}
print("{d}\n", .{output});
}
fn part2(reader: *std.Io.Reader, allocator: std.mem.Allocator) !void {
var output: usize = 0;
var list = try std.ArrayList([]u8).initCapacity(allocator, 0);
defer list.deinit(allocator);
while (reader.takeDelimiter('\n')) |line| {
if (line == null){
break;
}
try list.append(allocator, line.?);
} else |_| {
}
var previous_output: usize = 1;
while (output != previous_output) {
previous_output = output;
for (list.items,0..) |row, y| {
for (row,0..) |item,x| {
if (item != '@'){
continue;
}
var adjacent: usize = 0;
if (y > 0 and x > 0 and list.items[y - 1][x - 1] == '@') adjacent += 1;
if (y > 0 and list.items[y - 1][x] == '@') adjacent += 1;
if (y > 0 and x < row.len - 1 and list.items[y - 1][x + 1] == '@') adjacent += 1;
if (x > 0 and list.items[y][x - 1] == '@') adjacent += 1;
if (x < row.len - 1 and list.items[y][x + 1] == '@') adjacent += 1;
if (y < list.items.len - 1 and x > 0 and list.items[y + 1][x - 1] == '@') adjacent += 1;
if (y < list.items.len - 1 and list.items[y + 1][x] == '@') adjacent += 1;
if (y < list.items.len - 1 and x < row.len - 1 and list.items[y + 1][x + 1] == '@') adjacent += 1;
if (adjacent < 4){
list.items[y][x] = '.';
output += 1;
}
}
}
}
print("{d}\n", .{output});
}
|