4 "cell_type": "markdown",
7 "Given a sequence of {F|L|R}, each of which is \"move forward one step\", \"turn left, then move forward one step\", \"turn right, then move forward one step\":\n",
8 "1. which tours are closed?\n",
9 "2. what is the area enclosed by the tour?"
20 "import collections\n",
25 "import matplotlib.pyplot as plt\n",
37 "class Direction(enum.Enum):\n",
43 "turn_lefts = {Direction.UP: Direction.LEFT, Direction.LEFT: Direction.DOWN,\n",
44 " Direction.DOWN: Direction.RIGHT, Direction.RIGHT: Direction.UP}\n",
46 "turn_rights = {Direction.UP: Direction.RIGHT, Direction.RIGHT: Direction.DOWN,\n",
47 " Direction.DOWN: Direction.LEFT, Direction.LEFT: Direction.UP}\n",
49 "def turn_left(d):\n",
50 " return turn_lefts[d]\n",
52 "def turn_right(d):\n",
53 " return turn_rights[d]\n"
64 "Step = collections.namedtuple('Step', ['x', 'y', 'dir'])\n",
65 "Mistake = collections.namedtuple('Mistake', ['i', 'step'])"
76 "def advance(step, d):\n",
77 " if d == Direction.UP:\n",
78 " return Step(step.x, step.y+1, d)\n",
79 " elif d == Direction.DOWN:\n",
80 " return Step(step.x, step.y-1, d)\n",
81 " elif d == Direction.LEFT:\n",
82 " return Step(step.x-1, step.y, d)\n",
83 " elif d == Direction.RIGHT:\n",
84 " return Step(step.x+1, step.y, d)"
95 "def trace_tour(tour, startx=0, starty=0, startdir=Direction.RIGHT):\n",
96 " current = Step(startx, starty, startdir)\n",
97 " trace = [current]\n",
100 " current = advance(current, current.dir)\n",
102 " current = advance(current, turn_left(current.dir))\n",
104 " current = advance(current, turn_right(current.dir))\n",
105 " trace += [current]\n",
111 "execution_count": 6,
117 "def positions(trace):\n",
118 " return [(s.x, s.y) for s in trace]"
123 "execution_count": 7,
129 "def valid(trace):\n",
130 " return (trace[-1].x == 0 \n",
131 " and trace[-1].y == 0 \n",
132 " and len(set(positions(trace))) + 1 == len(trace))"
137 "execution_count": 8,
143 "def chunks(items, n=2):\n",
144 " return [items[i:i+n] for i in range(len(items) - n + 1)]"
148 "cell_type": "markdown",
151 "Using the [Shoelace formula](https://en.wikipedia.org/wiki/Shoelace_formula)"
156 "execution_count": 9,
162 "def shoelace(trace):\n",
163 " return abs(sum(s.x * t.y - t.x * s.y for s, t in chunks(trace, 2))) // 2"
168 "execution_count": 10,
174 "def step(s, current):\n",
176 " return advance(current, current.dir)\n",
178 " return advance(current, turn_left(current.dir))\n",
180 " return advance(current, turn_right(current.dir))\n",
187 "execution_count": 11,
193 "def valid_prefix(tour):\n",
194 " current = Step(0, 0, Direction.RIGHT)\n",
198 " current = step(s, current)\n",
200 " if (current.x, current.y) in posns:\n",
202 " elif current.x == 0 and current.y == 0: \n",
203 " return ''.join(prefix)\n",
204 " posns += [(current.x, current.y)]\n",
205 " if current.x == 0 and current.y == 0:\n",
206 " return ''.join(prefix)\n",
213 "execution_count": 12,
219 "def mistake_positions(trace, debug=False):\n",
221 " current = trace[0]\n",
222 " posns = [(0, 0)]\n",
223 " for i, current in enumerate(trace[1:]):\n",
224 " if (current.x, current.y) in posns:\n",
225 " if debug: print(i, current)\n",
226 " mistakes += [Mistake(i+1, current)]\n",
227 " posns += [(current.x, current.y)]\n",
228 " if (current.x, current.y) == (0, 0):\n",
229 " return mistakes[:-1]\n",
231 " return mistakes + [Mistake(len(trace)+1, current)]"
236 "execution_count": 13,
242 "def returns_to_origin(mistake_positions):\n",
243 " return [i for i, m in mistake_positions\n",
244 " if (m.x, m.y) == (0, 0)]"
249 "execution_count": 14,
255 "def random_walk(steps=1000):\n",
256 " return ''.join(random.choice('FFLR') for _ in range(steps))"
261 "execution_count": 15,
267 "def bounds(trace):\n",
268 " return (max(s.x for s in trace),\n",
269 " max(s.y for s in trace),\n",
270 " min(s.x for s in trace),\n",
271 " min(s.y for s in trace))"
276 "execution_count": 1,
280 "ename": "NameError",
281 "evalue": "name 'Direction' is not defined",
282 "output_type": "error",
284 "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
285 "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
286 "\u001b[0;32m<ipython-input-1-f5ea591d6161>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m plot_wh = {Direction.UP: (0, 1), Direction.LEFT: (-1, 0),\n\u001b[0m\u001b[1;32m 2\u001b[0m Direction.DOWN: (0, -1), Direction.RIGHT: (1, 0)}\n",
287 "\u001b[0;31mNameError\u001b[0m: name 'Direction' is not defined"
292 "plot_wh = {Direction.UP: (0, 1), Direction.LEFT: (-1, 0),\n",
293 " Direction.DOWN: (0, -1), Direction.RIGHT: (1, 0)}"
298 "execution_count": 16,
304 "def plot_trace(trace, colour='k', highlight_start=True,\n",
305 " xybounds=None, fig=None, subplot_details=None, filename=None):\n",
307 " plt.axes().set_aspect('equal')\n",
309 " if highlight_start:\n",
310 " plt.axes().add_patch(plt.Circle((trace[0].x, trace[0].y), 0.2, color=colour))\n",
312 " for s, t in chunks(trace, 2):\n",
313 " w, h = plot_wh[t.dir]\n",
314 " plt.arrow(s.x, s.y, w, h, head_width=0.1, head_length=0.1, fc=colour, ec=colour, length_includes_head=True)\n",
315 " xh, yh, xl, yl = bounds(trace)\n",
316 " if xybounds is not None: \n",
317 " bxh, byh, bxl, byl = xybounds\n",
318 " plt.xlim([min(xl, bxl)-1, max(xh, bxh)+1])\n",
319 " plt.ylim([min(yl, byl)-1, max(yh, byh)+1])\n",
321 " plt.xlim([xl-1, xh+1])\n",
322 " plt.ylim([yl-1, yh+1])\n",
324 " plt.savefig(filename)"
329 "execution_count": 17,
335 "def trim_loop(tour):\n",
336 " trace = trace_tour(tour)\n",
337 " mistakes = mistake_positions(trace)\n",
338 " end_mistake_index = 0\n",
339 "# print('end_mistake_index {} pointing to trace position {}; {} mistakes and {} in trace; {}'.format(end_mistake_index, mistakes[end_mistake_index].i, len(mistakes), len(trace), mistakes))\n",
340 " # while this mistake extends to the next step in the trace...\n",
341 " while (mistakes[end_mistake_index].i + 1 < len(trace) and \n",
342 " end_mistake_index + 1 < len(mistakes) and\n",
343 " mistakes[end_mistake_index].i + 1 == \n",
344 " mistakes[end_mistake_index + 1].i):\n",
345 "# print('end_mistake_index {} pointing to trace position {}; {} mistakes and {} in trace'.format(end_mistake_index, mistakes[end_mistake_index].i, len(mistakes), len(trace), mistakes))\n",
346 " # push this mistake finish point later\n",
347 " end_mistake_index += 1\n",
348 " mistake = mistakes[end_mistake_index]\n",
350 " # find the first location that mentions where this mistake ends (which the point where the loop starts)\n",
351 " mistake_loop_start = max(i for i, loc in enumerate(trace[:mistake.i])\n",
352 " if (loc.x, loc.y) == (mistake.step.x, mistake.step.y))\n",
353 "# print('Dealing with mistake from', mistake_loop_start, 'to', mistake.i, ', trace has len', len(trace))\n",
355 " # direction before entering the loop\n",
356 " direction_before = trace[mistake_loop_start].dir\n",
358 " # find the new instruction to turn from heading before the loop to heading after the loop\n",
359 " new_instruction = 'F'\n",
360 " if (mistake.i + 1) < len(trace):\n",
361 " if turn_left(direction_before) == trace[mistake.i + 1].dir:\n",
362 " new_instruction = 'L'\n",
363 " if turn_right(direction_before) == trace[mistake.i + 1].dir:\n",
364 " new_instruction = 'R'\n",
365 "# if (mistake.i + 1) < len(trace):\n",
366 "# print('turning from', direction_before, 'to', trace[mistake.i + 1].dir, 'with', new_instruction )\n",
368 "# print('turning from', direction_before, 'to BEYOND END', 'with', new_instruction )\n",
369 " return tour[:mistake_loop_start] + new_instruction + tour[mistake.i+1:]\n",
370 "# return mistake, mistake_loop_start, trace[mistake_loop_start-2:mistake_loop_start+8]"
375 "execution_count": 18,
381 "def trim_all_loops(tour, mistake_reduction_attempt_limit=10):\n",
382 " trace = trace_tour(tour)\n",
383 " mistake_limit = 1\n",
384 " if trace[-1].x == 0 and trace[-1].y == 0:\n",
385 " mistake_limit = 0\n",
386 " mistakes = mistake_positions(trace)\n",
388 " old_mistake_count = len(mistakes)\n",
389 " mistake_reduction_tries = 0\n",
391 " while len(mistakes) > mistake_limit and mistake_reduction_tries < mistake_reduction_attempt_limit:\n",
392 " tour = trim_loop(tour)\n",
393 " trace = trace_tour(tour)\n",
394 " mistakes = mistake_positions(trace)\n",
395 " if len(mistakes) < old_mistake_count:\n",
396 " old_mistake_count = len(mistakes)\n",
397 " mistake_reduction_tries = 0\n",
399 " mistake_reduction_tries += 1\n",
400 " if mistake_reduction_tries >= mistake_reduction_attempt_limit:\n",
408 "execution_count": 19,
414 "def reverse_tour(tour):\n",
415 " def swap(tour_step):\n",
416 " if tour_step == 'R':\n",
418 " elif tour_step == 'L':\n",
421 " return tour_step\n",
423 " return ''.join(swap(s) for s in reversed(tour))"
428 "execution_count": 20,
434 "def wander_near(locus, current, limit=10):\n",
435 " valid_proposal = False\n",
436 " while not valid_proposal:\n",
437 " s = random.choice('FFFRL')\n",
439 " proposed = advance(current, current.dir)\n",
441 " proposed = advance(current, turn_left(current.dir))\n",
443 " proposed = advance(current, turn_right(current.dir))\n",
444 " if abs(proposed.x - locus.x) < limit and abs(proposed.y - locus.y) < limit:\n",
445 " valid_proposal = True\n",
446 "# print('At {} going to {} by step {} to {}'.format(current, locus, s, proposed))\n",
447 " return s, proposed"
452 "execution_count": 21,
458 "def seek(goal, current):\n",
459 " dx = current.x - goal.x\n",
460 " dy = current.y - goal.y\n",
462 " if dx < 0 and abs(dx) > abs(dy): # to the left\n",
464 " if current.dir == Direction.RIGHT:\n",
466 " elif current.dir == Direction.UP:\n",
470 " elif dx > 0 and abs(dx) > abs(dy): # to the right\n",
472 " if current.dir == Direction.LEFT:\n",
474 " elif current.dir == Direction.UP:\n",
478 " elif dy > 0 and abs(dx) <= abs(dy): # above\n",
480 " if current.dir == Direction.DOWN:\n",
482 " elif current.dir == Direction.RIGHT:\n",
488 " if current.dir == Direction.UP:\n",
490 " elif current.dir == Direction.LEFT:\n",
495 " proposed = advance(current, current.dir)\n",
497 " proposed = advance(current, turn_left(current.dir))\n",
499 " proposed = advance(current, turn_right(current.dir))\n",
501 "# print('At {} going to {}, currently {}, by step {} to {}'.format(current, goal, side, s, proposed))\n",
503 " return s, proposed"
508 "execution_count": 22,
514 "def guided_walk(loci, locus_limit=5, wander_limit=10, seek_step_limit=20):\n",
516 " current = Step(0, 0, Direction.RIGHT) \n",
518 " finished = False\n",
519 " while not finished:\n",
520 " if abs(current.x - loci[l].x) < locus_limit and abs(current.y - loci[l].y) < locus_limit:\n",
522 " if l == len(loci) - 1:\n",
523 " finished = True\n",
524 " s, proposed = wander_near(loci[l], current, limit=wander_limit)\n",
526 " current = proposed\n",
527 "# print('!! Finished loci')\n",
529 " while not (current.x == loci[l].x and current.y == loci[l].y) and seek_steps < seek_step_limit:\n",
530 "# error = max(abs(current.x - loci[l].x), abs(current.y - loci[l].y))\n",
531 "# s, proposed = wander_near(loci[l], current, limit=error+1)\n",
532 " s, proposed = seek(loci[l], current)\n",
534 " current = proposed\n",
535 " seek_steps += 1\n",
536 " if seek_steps >= seek_step_limit:\n",
544 "execution_count": 24,
550 "def square_tour(a=80):\n",
551 " \"a is width of square\"\n",
552 " return ('F' * a + 'L') * 4"
557 "execution_count": 25,
563 "def cross_tour(a=50, b=40):\n",
564 " \"a is width of cross arm, b is length of cross arm\"\n",
565 " return ('F' * a + 'L' + 'F' * b + 'R' + 'F' * b + 'L') * 4"
570 "execution_count": 26,
576 "def quincunx_tour(a=60, b=30, c=50):\n",
577 " \"a is length of indent, b is indent/outdent distance, c is outdent outer length\"\n",
578 " return ('F' * a + 'R' + 'F' * b + 'L' + 'F' * c + 'L' + 'F' * c + 'L' + 'F' * b + 'R') * 4\n"
583 "execution_count": 27,
589 "heart_points = [Step(60, 50, Direction.UP), Step(50, 90, Direction.UP),\n",
590 " Step(20, 70, Direction.UP), \n",
591 " Step(-40, 90, Direction.UP), Step(-60, 80, Direction.UP), \n",
592 " Step(0, 0, Direction.RIGHT)]\n",
595 "current = Step(0, 0, Direction.RIGHT)\n",
597 "for hp in heart_points:\n",
598 " while not (current.x == hp.x and current.y == hp.y):\n",
599 " s, proposed = seek(hp, current)\n",
600 " heart_tour += s\n",
601 " current = proposed\n",
603 "def heart_tour_func(): return heart_tour"
608 "execution_count": 28,
614 "# success_count = 0\n",
615 "# while success_count <= 20:\n",
616 "# lc = trace_tour(square_tour(a=10))\n",
617 "# rw = guided_walk(lc, wander_limit=4, locus_limit=2)\n",
619 "# rw_trimmed = trim_all_loops(rw)\n",
620 "# if len(rw_trimmed) > 10:\n",
621 "# with open('small-squares.txt', 'a') as f:\n",
622 "# f.write(rw_trimmed + '\\n')\n",
623 "# success_count += 1"
628 "execution_count": 29,
634 "# success_count = 0\n",
635 "# while success_count <= 20:\n",
636 "# lc = trace_tour(square_tour())\n",
637 "# rw = guided_walk(lc)\n",
639 "# rw_trimmed = trim_all_loops(rw)\n",
640 "# if len(rw_trimmed) > 10:\n",
641 "# with open('large-squares.txt', 'a') as f:\n",
642 "# f.write(rw_trimmed + '\\n')\n",
643 "# success_count += 1"
648 "execution_count": 30,
654 "# success_count = 0\n",
655 "# while success_count <= 20:\n",
656 "# lc = trace_tour(cross_tour())\n",
657 "# rw = guided_walk(lc)\n",
659 "# rw_trimmed = trim_all_loops(rw)\n",
660 "# if len(rw_trimmed) > 10:\n",
661 "# with open('cross.txt', 'a') as f:\n",
662 "# f.write(rw_trimmed + '\\n')\n",
663 "# success_count += 1"
668 "execution_count": 31,
674 "# success_count = 0\n",
675 "# while success_count <= 20:\n",
676 "# lc = trace_tour(quincunx_tour())\n",
677 "# rw = guided_walk(lc)\n",
679 "# rw_trimmed = trim_all_loops(rw)\n",
680 "# if len(rw_trimmed) > 10:\n",
681 "# with open('quincunx.txt', 'a') as f:\n",
682 "# f.write(rw_trimmed + '\\n')\n",
683 "# success_count += 1"
688 "execution_count": 32,
694 "patterns = [square_tour, cross_tour, quincunx_tour, heart_tour_func]\n",
695 "tours_filename = 'tours.txt'\n",
698 " os.remove(tours_filename)\n",
702 "success_count = 0\n",
703 "while success_count < 100:\n",
704 " lc = trace_tour(random.choice(patterns)())\n",
705 " rw = guided_walk(lc)\n",
707 " rw_trimmed = trim_all_loops(rw)\n",
708 " if len(rw_trimmed) > 10:\n",
709 " with open(tours_filename, 'a') as f:\n",
710 " f.write(rw_trimmed + '\\n')\n",
711 " success_count += 1"
716 "execution_count": null,
726 "display_name": "Python 3",
727 "language": "python",
735 "file_extension": ".py",
736 "mimetype": "text/x-python",
738 "nbconvert_exporter": "python",
739 "pygments_lexer": "ipython3",