summaryrefslogtreecommitdiff
path: root/22.c
blob: 60b22913aabb9659bafde589581b1448053f0303 (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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#define _GNU_SOURCE

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


// Proper modulo operator
#define modulo(n, m) ((((n) % (m)) + (m)) % (m))


enum map_type {
	M_FLAT,
	M_NET,
};


enum direction {
	D_NORTH = 3,
	D_EAST = 0,
	D_SOUTH = 1,
	D_WEST = 2,
};


char const *
direction_name(enum direction dir)
{
	switch (dir) {
	case D_NORTH: return "North";
	case D_EAST: return "East";
	case D_SOUTH: return "South";
	case D_WEST: return "West";
	}
	return NULL;
}


// For each face of a cuboid, list adjoining faces in anti-clockwise order
//
// The faces are numbered as a right-handed six-sided die labelled 0 to 5.
// Opposite pairs add up to 5 (0/5, 1/4 and 2/3), and if you imagine curling the
// fingers of your right hand from the 0 to the 1, the 2 is on the face that
// your thumb is pointing to. e.g. if the 0 is on the front, and the 1 is on
// top, the 2 is on the left side.
//
// When a face is "oriented" a certain way, then if that face is on top, the
// first adjoining face listed in table below is in that direction.
//
// e.g. If the 3 face is on the top of the cuboid and "oriented" west, then the
// 4 face is to its west, the 5 is to its south, the 1 is to its east, and the 0
// is to its north.
static int const faceids[6][4] = {
	{ 1, 2, 4, 3 },		// 0 sees 1, 2, 4, 3
	{ 0, 3, 5, 2 },		// 1 sees 0, 3, 5, 2
	{ 5, 4, 0, 1 },		// 2 sees 5, 4, 0, 1
	{ 4, 5, 1, 0 },		// 3 sees 4, 5, 1, 0
	{ 3, 0, 2, 5 },		// 4 sees 3, 0, 2, 5
	{ 2, 1, 3, 4 },		// 5 sees 2, 1, 3, 4
};


// Given an oriented top face, which face do we see in a given direction?
int
faceid_look(int topid, enum direction orient, enum direction look)
{
	static enum direction const dirs[] = { D_NORTH, D_WEST, D_SOUTH, D_EAST };
	int topdir, destdir;

	if (topid < 0 || topid >= 6)
		return -1;

	// Go through `dirs` until we find the one that topid is pointing to
	for (topdir = 0; topdir < 4; ++topdir)
		if (dirs[topdir % 4] == orient)
			break;
	if (topdir >= 4)
		return -1;

	// Keep going through `dirs` until we find the one that the caller wants
	for (destdir = topdir; destdir < topdir + 4; ++destdir)
		if (dirs[destdir % 4] == look)
			break;
	if (destdir >= topdir + 4)
		return -1;

	// Look up the destination face id.
	return faceids[topid][destdir - topdir];
}


// Given an oriented top face, which direction do we look to see another face?
enum direction
faceid_find(int topid, enum direction orient, int destid)
{
	static enum direction const dirs[] = { D_NORTH, D_WEST, D_SOUTH, D_EAST };
	int topdir, destix;

	// Go through the directions until we find the one that fsrc is pointing
	for (topdir = 0; topdir < 4; ++topdir)
		if (dirs[topdir % 4] == orient)
			break;
	if (topdir >= 4)
		return -1;

	// Go through topid's faces until we find destid
	for (destix = 0; destix < 4; ++destix)
		if (faceids[topid][destix] == destid)
			break;
	if (destix >= 4)
		return -1;

	// Return the direction that dest should be in
	return dirs[(topdir + destix) % 4];
}


// Given a top face, if we see another face in one direction, what is the
// orientation of the top face?
enum direction
faceid_orientation(int topid, int destid, enum direction destdir)
{
	static enum direction const dirs[] = { D_NORTH, D_WEST, D_SOUTH, D_EAST };
	int topdir, destix;

	// Go through topid's faces until we find destid
	for (destix = 0; destix < 4; ++destix)
		if (faceids[topid][destix] == destid)
			break;
	if (destix >= 4)
		return -1;

	// From faceid_find(), if dirs[topdir + destix] points to destdir,
	// then we just go through possible topdirs until we find the one
	// that makes this true
	for (topdir = 0; topdir < 4; ++topdir)
		if (dirs[(topdir + destix) % 4] == destdir)
			break;
	if (topdir >= 4)
		return -1;

	// Return the direction that dest should be in
	return dirs[topdir];
}


struct point {
	int x;
	int y;
};


struct point *
point_init(struct point * pt, int x, int y)
{
	pt->x = x;
	pt->y = y;
	return pt;
}


struct map {
	char * _buf;
	int cols;
	int rows;
	enum map_type type;
};


int map_outline(struct point ** outline, struct map const * map);


// Initialise a map from a buffer.
//
// The map takes ownership of the buffer from when it's called, whether
// or not the initialisation is successful
struct map *
map_init(struct map * map, char * buf, size_t buflen, enum map_type type)
{
	char * beg, * end;
	long pos;

	map->_buf = NULL;
	map->cols = 0;
	map->rows = 0;
	map->type = type;

	// Work out max lines and longest line.
	for (beg = buf; beg < buf + buflen; beg = end + 1, ++map->rows) {
		end = memchr(beg, '\n', buf + buflen - beg);
		if (end - beg > map->cols)
			map->cols = end - beg;
	}
	if (map->cols == 0 || map->rows == 0) {
		fprintf(stderr, "Unexpected map size (%d,%d)\n", map->cols, map->rows);
		free(buf);
		return NULL;
	}
	++map->cols; // Also count the newline on the end of each line.

	// Resize the map data buffer to hold a full grid of data
	if ((map->_buf = realloc(buf, map->cols * map->rows)) == NULL) {
		fprintf(stderr, "Bad realloc(%d)\n", map->cols * map->rows);
		free(buf);
		return NULL;
	}
	memset(map->_buf + buflen, ' ', map->cols * map->rows - buflen);

	// Move the map data so that it fits the grid properly
	for (end = map->_buf + buflen, pos = map->rows - 1; pos >= 0; end = beg, --pos) {
		beg = memrchr(map->_buf, '\n', (end - map->_buf) - 1);
		beg = beg ? beg + 1 : map->_buf;
		memmove(map->_buf + pos * map->cols, beg, (end - beg));
		memset(map->_buf + (pos * map->cols) + (end - beg) - 1, ' ', map->cols - (end - beg) + 1);
		map->_buf[pos * map->cols + map->cols - 1] = '\n';
	}

	if (map->type == M_NET) {
		struct point * outline;
		int len;

		if ((len = map_outline(&outline, map)) < 0) {
			free(map->_buf);
			return NULL;
		}

		fprintf(stderr, "Outline has %d corners\n", len - 1);

		free(outline);
	}

	return map;
}


void
map_tidy(struct map * map)
{
	if (!map)
		return;

	free(map->_buf);
	return;
}


int
map_elem(struct map const * map, int x, int y)
{
	if (x < 0 || x >= map->cols - 1
			|| y < 0 || y >= map->rows)
		return ' ';

	return map->_buf[x + (map->rows - 1 - y) * map->cols];
}


// Get the outline of the map, anti-clockwise
//
// Note that for lengths to be correct, as we're tracing south and east we keep
// inside the map, but as we're tracing north and west we keep one element
// outside the map.
//
// Duplicates the first/last corner, because this makes some things easier.
//
// Returns number of corners found (including duplicate), or -1 on error
int
map_outline(struct point ** outline, struct map const * map)
{
	struct point * pt;
	int len = 2;
	enum direction dir;

	if ((*outline = malloc(len * sizeof(struct point))) == NULL) {
		fprintf(stderr, "%s: Bad malloc(%ld)\n",
				__FUNCTION__, len * sizeof(struct point));
		return -1;
	}

	// Start from the top-left, because we know there has to be a
	// starting point for the elf there, and head south.
	pt = *outline;
	point_init(pt, 0, map->rows - 1);
	while (map_elem(map, pt->x, pt->y) == ' ')
		++pt->x;
	++pt->y;
	dir = D_SOUTH;

	while (1) {
		struct point pt_move, pt_left, pt_right;
		enum direction turn_left, turn_right;

		// Based on which direction we're going, figure out how to move
		// forward, which elements to look at to decide if we need to
		// turn left or right, and which way is left and right.
		switch (dir) {
		case D_NORTH:
			point_init(&pt_move, 0, 1);
			point_init(&pt_left, -1, 0);
			point_init(&pt_right, 0, 0);
			turn_left = D_WEST;
			turn_right = D_EAST;
			break;

		case D_SOUTH:
			point_init(&pt_move, 0, -1);
			point_init(&pt_left, 0, -1);
			point_init(&pt_right, -1, -1);
			turn_left = D_EAST;
			turn_right = D_WEST;
			break;

		case D_EAST:
			point_init(&pt_move, 1, 0);
			point_init(&pt_left, 0, 0);
			point_init(&pt_right, 0, -1);
			turn_left = D_NORTH;
			turn_right = D_SOUTH;
			break;

		case D_WEST:
			point_init(&pt_move, -1, 0);
			point_init(&pt_left, -1, -1);
			point_init(&pt_right, -1, 1);
			turn_left = D_SOUTH;
			turn_right = D_NORTH;
			break;
		}

		// Move forward until we need to turn
		pt = *outline + len - 1;
		point_init(pt, (pt - 1)->x, (pt - 1)->y);
		while (1) {
			pt->x += pt_move.x;
			pt->y += pt_move.y;

			if (map_elem(map, pt->x + pt_left.x, pt->y + pt_left.y) == ' ') {
				dir = turn_left;
				break;
			}
			if (map_elem(map, pt->x + pt_right.x, pt->y + pt_right.y) != ' ') {
				dir = turn_right;
				break;
			}
		}

		// Is the turning point back at the start? If so, we're done.
		if (len > 4 && pt->x == (*outline)->x && pt->y == (*outline)->y)
			return len;

		// Sanity check
		if (len > 100) {
			fprintf(stderr, "%s: Too many corners (%d)!\n",
					__FUNCTION__, len);
			free(*outline);
			*outline = NULL;
			return -1;
		}

		// No? OK, add a new point to check for.
		++len;
		if ((pt = realloc(*outline, len * sizeof(struct point))) == NULL) {
			fprintf(stderr, "%s: Bad realloc(%ld)\n",
					__FUNCTION__, len * sizeof(struct point));
			free(*outline);
			*outline = NULL;
			return -1;
		}
		*outline = pt;
	}

	fprintf(stderr, "%s: Unreachable!\n", __FUNCTION__);
	free(*outline);
	*outline = NULL;
	return -1;
}


struct elf {
	int x;
	int y;
	enum direction dir;
};


int
elf_turn(struct elf * elf, char turn)
{
#define direction_go(d, t) (1000 * (d) + (t))

	switch (direction_go(elf->dir, turn)) {
	case direction_go(D_NORTH, 'R'):
	case direction_go(D_SOUTH, 'L'):
		elf->dir = D_EAST;
		break;

	case direction_go(D_NORTH, 'L'):
	case direction_go(D_SOUTH, 'R'):
		elf->dir = D_WEST;
		break;

	case direction_go(D_EAST, 'L'):
	case direction_go(D_WEST, 'R'):
		elf->dir = D_NORTH;
		break;

	case direction_go(D_EAST, 'R'):
	case direction_go(D_WEST, 'L'):
		elf->dir = D_SOUTH;
		break;

	default:
		fprintf(stderr, "Unexpected elf_turn(%d, %c)\n", elf->dir, turn);
		return -1;
	}

	return 0;

#undef direction_go
}


int
elf_move(struct elf * elf, struct map const * map, int distance)
{
	while (distance > 0) {
		int dx = 0, dy = 0, elem;
		struct elf newelf;

		switch (elf->dir) {
		case D_NORTH: dy = +1; break;
		case D_SOUTH: dy = -1; break;
		case D_EAST: dx = +1; break;
		case D_WEST: dx = -1; break;
		default:
			fprintf(stderr, "Unexpected direction %d\n", elf->dir);
			return -1;
		}

		switch (map->type) {
		case M_FLAT:
			newelf.x = modulo(elf->x + dx, map->cols);
			newelf.y = modulo(elf->y + dy, map->rows);
			newelf.dir = elf->dir;
			elem = map_elem(map, newelf.x, newelf.y);

			// Just keep going until we wrap around to a non-blank position
			while (elem == ' ') {
				newelf.x = modulo(newelf.x + dx, map->cols);
				newelf.y = modulo(newelf.y + dy, map->rows);
				elem = map_elem(map, newelf.x, newelf.y);
			}
			break;

		case M_NET:
			fprintf(stderr, "Map type not yet supported!\n");
			return -1;

		default:
			fprintf(stderr, "Unknown map type %d\n", map->type);
			return -1;
		}

		switch (elem) {
		case '.':
			*elf = newelf;
			--distance;
			break;

		case '#':
			distance = 0;
			break;

		default:
			fprintf(stderr, "Unexpected map character %c\n", elem);
			return -1;
		}
	}

	return 0;
}


int
main(int argc, char ** argv)
{
	char * buf = NULL;
	struct map map;
	enum map_type mtype = M_FLAT;
	long bufsiz = 0, buflen = 0;
	struct elf elf;
	char distance[8];
	int c, dlen = 0;

	while ((c = getopt(argc, argv, "p:m:")) != -1) {
		switch (c) {
		case 'p':
			switch (atoi(optarg)) {
			case 1:
				mtype = M_FLAT;
				break;

			case 2:
				mtype = M_NET;
				break;

			default:
				fprintf(stderr, "Unexpected puzzle part %s\n", optarg);
				return -1;
			}
			break;

		case 'm':
			if (strcmp(optarg, "flat") == 0) {
				mtype = M_FLAT;
			}
			else if (strcmp(optarg, "net") == 0) {
				mtype = M_NET;
			}
			else {
				fprintf(stderr, "Unexpected map type %s\n", optarg);
				return -1;
			}
			break;

		default:
			return -1;
		}
	}

	// Read map data
	// Don't try and figure out lines yet, in case we get a line longer than
	// our read buffer, which could make things awkward.
	while (1) {
		if (bufsiz - buflen < BUFSIZ / 2) {
			void * p;
			bufsiz += BUFSIZ;
			if ((p = realloc(buf, bufsiz)) == NULL) {
				fprintf(stderr, "Bad realloc(%ld)\n", bufsiz);
				free(buf);
				return -1;
			}
			buf = p;
		}

		if (!fgets(buf + buflen, bufsiz - buflen, stdin))
			// End of file!
			break;

		if (buflen > 0 && buf[buflen] == '\n' && buf[buflen - 1] == '\n')
			// End of map input.
			break;

		buflen += strlen(buf + buflen);
	}

	if (map_init(&map, buf, buflen, mtype) == NULL) {
		fprintf(stderr, "Failed to initialise map\n");
		return -1;
	}

	// Set initial position
	elf.x = 0;
	elf.y = map.rows - 1;
	elf.dir = D_EAST;
	while (elf.x < map.cols && map_elem(&map, elf.x, elf.y) != '.')
		++elf.x;

	// Read and follow the movement instructions.
	while (elf.x >= 0 && (c = fgetc(stdin)) != EOF) {
		if (isdigit(c)) {
			distance[dlen++] = c;
		}
		else if (c == 'L' || c == 'R') {
			distance[dlen] = '\0';

			if (elf_move(&elf, &map, atoi(distance)) != 0)
				elf.x = -1;
			if (elf_turn(&elf, c) != 0)
				elf.x = -1;

			dlen = 0;
		}
		else if (c == '\n') {
			// Cover last bit of distance, if any
			distance[dlen] = '\0';
			if (elf_move(&elf, &map, atoi(distance)) != 0)
				elf.x = -1;
			break;
		}
		else {
			fprintf(stderr, "Unexpected movement instruction (%c)\n", c);
			map_tidy(&map);
			return -1;
		}
	}
	if (elf.x < 0) {
		map_tidy(&map);
		return -1;
	}

	// Done.
	printf("Password is %d (%d,%d,%d)\n",
			1000 * (map.rows - elf.y) + 4 * (1 + elf.x) + elf.dir,
			1 + elf.x, map.rows - elf.y, elf.dir);

	// Tidy and exit.
	map_tidy(&map);

	return 0;
}