aboutsummaryrefslogtreecommitdiff
path: root/2017/03/puzzle-2.awk
blob: 07586581e120255cd640d64e4bdf959fdc93d00e (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
#!/usr/bin/env -S awk -f

function move(xi, yi)
{
	for (k = 0; k < j; k++) {
		if (xi)
			x += xi
		else
			y += yi

		spiral[y][x] = spiral[y][x - 1] + spiral[y][x + 1] + spiral[y + 1][x + 1] \
				+ spiral[y + 1][x] + spiral[y + 1][x - 1] + spiral[y - 1][x + 1] \
				+ spiral[y - 1][x] + spiral[y - 1][x - 1]
		if (spiral[y][x] > n)
			return spiral[y][x]
	}
	return 0
}

{ n = $1 }

END {
	spiral[0][0] = 1
	x = y = 0
	j = 1
	for (i = 1; 1; i++) {
		if (i % 2)
			if (r = move(j % 2 ? 1 : -1, 0))
				break
		else {
			if (r = move(0, j % 2 ? 1 : -1))
				break
			j++
		}
	}

	print r
}