summary refs log tree commit diff homepage
path: root/2022/day14.awk
blob: 7cf90ad6bb903b1d954e5b7ed0b7229d097d2884 (plain) (blame)
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
BEGIN {
	FS = "[ ,>-]+";
}
{
	x = $1;
	y = $2;
	for (i = 3; i <= NF; i += 2) {
		tx = $i;
		ty = $(i+1);
		while (x != tx) {
			m[x,y] = "#";
			if (x < tx) x++;
			if (x > tx) x--;
		}
		while (y != ty) {
			m[x,y] = "#";
			if (y < ty) y++;
			if (y > ty) y--;
		}
		m[x,y] = "#";
		if (y > ymax) ymax = y;
	}
}
END {
	x = 500;
	y = 0;
	while (y < ymax) {
		if (!m[x,y+1]) {
			y++;
		} else if (!m[x-1,y+1]) {
			x--;
			y++;
		} else if (!m[x+1,y+1]) {
			x++;
			y++;
		} else {
			m[x,y] = "o";
			sand++;
			x = 500;
			y = 0;
		}
	}
	print sand;
	for (xy in m) {
		if (m[xy] == "o") delete m[xy];
	}
	sand = 0;
	while (!m[500,0]) {
		if (!m[x,y+1] && y+1 != ymax+2) {
			y++;
		} else if (!m[x-1,y+1] && y+1 != ymax+2) {
			x--;
			y++;
		} else if (!m[x+1,y+1] && y+1 != ymax+2) {
			x++;
			y++;
		} else {
			m[x,y] = "o";
			sand++;
			x = 500;
			y = 0;
		}
	}
	print sand;
}