aboutsummaryrefslogtreecommitdiff
path: root/2017/03/puzzle-1.c
blob: 00cebd731fbcbd1088ec2a8253a897c1a6c0281a (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
#include <err.h>
#include <stdio.h>
#include <stdlib.h>

#define ODD(x) (x & 1)
#define MOVE(x)                                                                                    \
	do {                                                                                       \
		for (int k = 0; k < j; k++) {                                                      \
			x;                                                                         \
			if (++m == n)                                                              \
				goto out;                                                          \
		}                                                                                  \
	} while (0)

int
main(void)
{
	int n, x, y;
	FILE *fp;

	if (!(fp = fopen("input", "r")))
		err(EXIT_FAILURE, "fopen");

	fscanf(fp, "%d", &n);
	fclose(fp);

	x = y = 0;
	for (int i = 1, m = 1, j = 1; i < n; i++) {
		if (ODD(i)) {
			if (ODD(j))
				MOVE(x++);
			else
				MOVE(x--);
		} else {
			if (ODD(j))
				MOVE(y++);
			else
				MOVE(y--);
			j++;
		}
	}
out:
	if (x < 0)
		x = -x;
	if (y < 0)
		y = -y;

	printf("%d\n", x + y);
	return EXIT_SUCCESS;
}