summaryrefslogtreecommitdiff
path: root/day4/part2/main.ha
blob: 5e1d10a7210acf018eda3bbe22937557786383bf (plain)
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
use fmt;
use io;
use os;
use strconv;
use strings::{fromutf8_unsafe, split, torunes};

const adjacent_positions: [8][2]int = [
	[-1, -1],
	[ 0, -1],
	[ 1, -1],
	[-1,  0],
	[ 1,  0],
	[-1,  1],
	[ 0,  1],
	[ 1,  1]
];

fn adjacent_rolls(grid: [][]rune, x: int, y: int) u64 = {
	let rolls: u64 = 0;

	for (let pos .. adjacent_positions) {
		let col = x: int + pos[0];
		let row = y: int + pos[1];

		if (col < 0 || col >= len(grid[0]): int ||
			row < 0 || row >= len(grid): int)
			continue;


		if (grid[row][col] == '@')
			rolls += 1;
	};

	return rolls;
};

export fn main() void = {
	let handle = os::open("input.txt")!;
	defer io::close(handle)!;

	let buf = io::drain(handle)!;
	defer free(buf);

	let lines = split(fromutf8_unsafe(buf), "\n")!;
	let grid: [][]rune = [];

	let total_removable_rolls: u64 = 0;
	let removed_rolls: u64 = 666;

	for (let line .. lines) {
		if (line != "")
			append(grid, torunes(line)!)!;
	};

	for (removed_rolls > 0) {
		removed_rolls = 0;
		for (let x: size = 0; x < len(grid[0]); x += 1) {
			for (let y: size = 0; y < len(grid); y += 1) {
				if (grid[y][x] == '@' &&
					adjacent_rolls(grid, x: int, y: int) < 4) {
					grid[y][x] = '.';
					total_removable_rolls += 1;
					removed_rolls += 1;
				};
			};
		};
	};

	fmt::printfln("Answer: {}", total_removable_rolls)!;
};