19 "def pancake_sort(items, debug=False):\n",
20 " if len(items) <= 1:\n",
21 " if debug: print('{} -> {}: {}'.format(items, items, []))\n",
22 " return items, []\n",
23 " elif len(items) == 2:\n",
24 " if items[0] < items[1]:\n",
25 " if debug: print('{} -> {}: {}'.format(items, items, []))\n",
26 " return items, []\n",
28 " if debug: print('{} -> {}: {}'.format(items, list(reversed(items)), [2]))\n",
29 " return list(reversed(items)), [2]\n",
31 " largest = max(items)\n",
32 " largest_index = items.index(largest)\n",
34 " if largest_index == len(items) - 1:\n",
36 " elif largest_index == 0:\n",
37 " items1 = list(reversed(items))\n",
38 " flips = [len(items)]\n",
39 " else: # largest_index > 0\n",
40 " items1 = list(reversed(list(reversed(items[:largest_index+1])) + items[largest_index+1:]))\n",
41 " flips = [largest_index + 1, len(items)]\n",
42 " if debug: print('{} -> {}: {}'.format(items, items1, flips))\n",
43 " sorted_items, sorting_flips = pancake_sort(items1[:-1], debug=debug)\n",
44 " return sorted_items + items1[-1:], flips + sorting_flips"
53 "def enflip(items, flips, burnt=False, debug=False):\n",
54 " if debug: i0 = items\n",
55 " for flip in flips:\n",
57 " items = [-i for i in reversed(items[:flip])] + items[flip:]\n",
59 " items = [i for i in reversed(items[:flip])] + items[flip:]\n",
60 " if debug: print('{} -{}-> {}'.format(i0, flip, items))\n",
61 " if debug: i0 = items\n",
64 "def unflip(items, flips, burnt=False, debug=False):\n",
65 " return enflip(items, reversed(flips), burnt=burnt, debug=debug)"
74 "def pancake_adjacent(higher, lower, sorted_items):\n",
75 " if sorted_items.index(higher) == sorted_items.index(lower) - 1:\n",
87 "def pancake_chunks(items):\n",
88 " atoms = [[i] for i in items]\n",
89 " sorted_items = list(sorted(items))\n",
90 " return coalesce(atoms)"
99 "def coalesce(chunks):\n",
100 " items = sorted(merge_chunks(chunks), key=abs)\n",
102 " while i < (len(chunks) - 1):\n",
103 " last_index = items.index(chunks[i][-1])\n",
104 " next_index = items.index(chunks[i+1][0])\n",
105 " if chunks[i][-1] > 0 and chunks[i+1][0] > 0 and last_index + 1 == next_index:\n",
106 " chunks = chunks[:i] + [chunks[i] + chunks[i+1]] + chunks[i+2:]\n",
107 " elif chunks[i][-1] < 0 and chunks[i+1][0] < 0 and last_index - 1 == next_index:\n",
108 " chunks = chunks[:i] + [chunks[i] + chunks[i+1]] + chunks[i+2:]\n",
116 "execution_count": 7,
120 "def chunk_bases(chunks):\n",
121 " return [c[-1] if c[-1] > 0 else c[0] for c in chunks]"
126 "execution_count": 8,
130 "def merge_chunks(chunks):\n",
131 " return [i for c in chunks for i in c]"
136 "execution_count": 9,
140 "def chunk_count_to_item_count(chunks, cpos):\n",
141 "# print(chunks, cpos, chunks[:cpos])\n",
142 " return len(merge_chunks(chunks[:cpos]))"
147 "execution_count": 10,
151 "def chunk_index(chunks, item):\n",
152 " \"\"\"Return the index of the first chunk containing item\"\"\"\n",
153 " return [i for i, c in enumerate(chunks) if item in c][0]"
158 "execution_count": 11,
162 "def enflip_chunks(chunks, flips, debug=False):\n",
163 " if debug: c0 = chunks\n",
164 " for flip in flips:\n",
165 " chunks = [[-i for i in reversed(c)] for c in reversed(chunks[:flip])] + chunks[flip:]\n",
166 " if debug: print('{} ={}=> {}'.format(c0, flip, chunks))\n",
167 " if debug: c0 = chunks\n",
170 "def unflip_chunks(chunks, flips, debug=False):\n",
171 " return enflip(chunks, reversed(flips), debug=debug)"
176 "execution_count": 12,
180 "def burnt_pancake_step_case1(chunks, all_chunks, items, largest, largest_burntdown, debug=False):\n",
181 " largest_burntdown_index = chunk_index(chunks, largest_burntdown)\n",
182 " if largest_burntdown == largest: # case 1(c): largest pancake is facedown, move to bottom of stack\n",
183 " cflips = [largest_burntdown_index + 1, len(chunks)]\n",
184 " flips = [items.index(largest_burntdown) + 1, len(merge_chunks(chunks))]\n",
185 " done_chunks = enflip_chunks(chunks, cflips, debug=debug)\n",
187 " largest_burntdown_partner = max(i for i in chunk_bases(chunks) if abs(i) > largest_burntdown)\n",
188 " largest_burntdown_partner_index = chunk_index(chunks, largest_burntdown_partner)\n",
189 " if largest_burntdown_partner_index > largest_burntdown_index: # case 1(a): partner is lower than this\n",
190 " chunks1 = enflip_chunks(all_chunks, [largest_burntdown_partner_index + 1], debug=debug)\n",
191 " new_lb_pos = chunk_index(chunks1, -largest_burntdown)\n",
192 " done_chunks = enflip_chunks(chunks1, [new_lb_pos], debug=debug)\n",
193 " flips = [chunk_count_to_item_count(all_chunks, largest_burntdown_partner_index + 1), \n",
194 " chunk_count_to_item_count(chunks1, new_lb_pos)]\n",
195 " else: # case 1(b): partner is higher than this\n",
196 " chunks1 = enflip_chunks(chunks, [largest_burntdown_index + 1], debug=debug)\n",
197 " new_lbi_pos = chunk_index(chunks1, -largest_burntdown_partner)\n",
198 " done_chunks = enflip_chunks(chunks1, [new_lbi_pos], debug=debug)\n",
199 " flips = [chunk_count_to_item_count(chunks, largest_burntdown_index + 1), \n",
200 " chunk_count_to_item_count(chunks1, new_lbi_pos)]\n",
201 " return coalesce(done_chunks), flips"
206 "execution_count": 13,
210 "def burnt_pancake_step_case2(chunks, all_chunks, debug=False):\n",
211 " items = merge_chunks(chunks)\n",
213 " if items == list(reversed(sorted(items))): # invoke -I special case\n",
214 " if debug: print(\"2: -I\")\n",
216 " flips = [f for fp in [[n, n-1] for _ in range(n)] for f in fp if f != 0]\n",
217 " done_items = enflip(items, flips, burnt=True, debug=debug)\n",
218 " done_chunks = pancake_chunks(done_items)\n",
219 " elif items == sorted(items): # items are in reverse order, upside down\n",
220 " if debug: print(\"2: rev\")\n",
221 " flips = [len(items)]\n",
222 " done_items = enflip(items, flips, burnt=True, debug=debug)\n",
223 " done_chunks = pancake_chunks(done_items)\n",
225 " candidates = chunk_bases(chunks)\n",
226 " largest_unsorted = min(candidates)\n",
227 " next_largest_unsorted = min(i for i in candidates if i > largest_unsorted)\n",
228 " largest_unsorted_index = chunk_index(chunks, largest_unsorted)\n",
229 " next_largest_unsorted_index = chunk_index(chunks, next_largest_unsorted)\n",
230 "# print(largest_unsorted, next_largest_unsorted, largest_unsorted_index, next_largest_unsorted_index)\n",
231 " while next_largest_unsorted_index > largest_unsorted_index:\n",
232 " largest_unsorted = next_largest_unsorted\n",
233 " largest_unsorted_index = next_largest_unsorted_index\n",
234 " next_largest_unsorted = min(i for i in candidates if i > largest_unsorted)\n",
235 " next_largest_unsorted_index = chunk_index(chunks, next_largest_unsorted)\n",
236 " if debug: print(\"2: general, lu = {}, nlu = {}\".format(largest_unsorted, next_largest_unsorted))\n",
237 " chunks1 = enflip_chunks(chunks, [largest_unsorted_index + 1])\n",
238 " done_chunks = enflip_chunks(chunks1, [next_largest_unsorted_index], debug=debug)\n",
239 "# cflips = [largest_unsorted_index + 1, next_largest_unsorted_index]\n",
240 " flips = [chunk_count_to_item_count(chunks, largest_unsorted_index + 1), \n",
241 " chunk_count_to_item_count(chunks1, next_largest_unsorted_index)]\n",
242 "# done_chunks = enflip_chunks(chunks, cflips, debug=debug)\n",
243 " return coalesce(done_chunks), flips"
248 "execution_count": 14,
252 "def burnt_pancake_step(chunks0, items, debug=False):\n",
253 " chunks = chunks0\n",
254 " largest = max(abs(i) for c in chunks for i in c)\n",
255 " while chunks[-1][-1] >= largest:\n",
256 " chunks = chunks[:-1]\n",
257 " largest = max(abs(i[-1]) for i in chunks)\n",
258 " largest_burntdown = max(merge_chunks(chunks))\n",
259 " if debug: print('<<', chunks, chunks0, items, largest, largest_burntdown)\n",
260 " if largest_burntdown > 0:\n",
261 " return burnt_pancake_step_case1(chunks, chunks0, items, largest, largest_burntdown, debug=debug)\n",
263 " return burnt_pancake_step_case2(chunks, chunks0, debug=debug)"
268 "execution_count": 15,
272 "def burnt_pancake_sort(items, fudge_rate=0, debug=False):\n",
274 " flip_limit = len(items) * 3\n",
276 " chunks = pancake_chunks(items)\n",
277 " while (any(i for i in items if i < 0) or sorted(items) != items) and len(flips) < flip_limit:\n",
278 " chunks, these_flips = burnt_pancake_step(chunks, items, debug=debug)\n",
279 " if debug: print('Got chunks:', chunks)\n",
280 " items = merge_chunks(chunks)\n",
281 " flips += these_flips\n",
282 " if random.random() < fudge_rate:\n",
283 " if debug: c_old = chunks\n",
284 " its = [abs(i) for i in merge_chunks(chunks)]\n",
285 " eits = sorted(i for i in items0 if i not in its)\n",
286 " chunks = coalesce(pancake_chunks(its + eits))\n",
287 " items = its + eits\n",
288 " if debug: print('!! Fudge: Converting {} to {}'.format(c_old, chunks))\n",
289 " return items, flips"
294 "execution_count": 16,
298 "def equiv_case(base_unsorted, flips, burnt=False, max_value=10000):\n",
299 "# new_sample = random.sample(list(range(1, max_value)), k=len(base_unsorted))\n",
301 " while not valid:\n",
302 " new_sample = random.sample(list(range(1, max_value)), k=len(base_unsorted))\n",
303 " valid = len(new_sample) == len(base_unsorted)\n",
304 " sample = sorted(new_sample)\n",
305 " return unflip(sample, flips, burnt=burnt)"
310 "execution_count": 17,
314 "def burnt_sorted(pancakes):\n",
315 " return pancakes == sorted(pancakes)\n",
317 "def unburnt_sorted(pancakes):\n",
318 " simple_pancakes = [abs(p) for p in pancakes]\n",
319 " return simple_pancakes == sorted(simple_pancakes)"
324 "execution_count": 18,
328 "def inverted_count(pancakes):\n",
329 " return sum(1 for p in pancakes if p < 0)"
334 "execution_count": 19,
338 "def cache_flips(start, flips, burnt=False):\n",
339 " positions = [{'pos': start}]\n",
341 " for f in flips:\n",
342 " stack = enflip(stack, [f], burnt=burnt)\n",
343 " positions += [{'pos': stack, 'move': f}]\n",
349 "execution_count": 20,
353 "def show_cached_flips(cache):\n",
354 " rows = len(cache[0]['pos'])\n",
355 " middle_row = (rows) // 2\n",
356 " for r in range(rows):\n",
357 " for c in cache:\n",
358 " if r == middle_row and 'move' in c:\n",
359 " print(' -{}-> '.format(c['move']), end='')\n",
360 " elif 'move' in c:\n",
361 " print(' ', end='')\n",
362 " if c['pos'][r] > 0:\n",
363 " print('{:2d} '.format(c['pos'][r]), end='')\n",
365 " print('{:2d}*'.format(abs(c['pos'][r])), end='')\n",
370 "cell_type": "markdown",
373 "Approach to developing test cases:\n",
375 "1. Find a random pancake stack.\n",
376 "2. Find the burnt pancake sort of that stack: `burnt_flips`\n",
377 "3. Find an equivalent case for those flips: `pancakes`\n",
378 "4. Find a bunch of fudged burnt sorts of the `pancakes`: `fudged`\n",
379 "5. Find a bunch of random fudged pancake sorts: `padding`\n",
381 "To assemble the test case, join together:\n",
382 "* the `burnt_flips`\n",
384 "* enough `padding` to make a round number."
389 "execution_count": 21,
398 "execution_count": 21,
400 "output_type": "execute_result"
406 "fudge_rate = 0.3\n",
408 "start = [i for i in random.sample(list(range(1, ln+1)), k=ln)]\n",
410 "_, test_flips['burnt_flips'] = burnt_pancake_sort(start)\n",
411 "test_flips['pancakes'] = equiv_case(start, test_flips['burnt_flips'], burnt=True)\n",
412 "test_flips['fudged'] = [burnt_pancake_sort(start, fudge_rate=fudge_rate)[1] for _ in range(n_equivs)]\n",
413 "test_flips['padding'] = [burnt_pancake_sort(random.sample(list(range(1, ln+1)), k=ln), fudge_rate=fudge_rate)[1] for _ in range(n_equivs)]\n",
419 "execution_count": 22,
428 "execution_count": 22,
430 "output_type": "execute_result"
434 "test_data = [test_flips['burnt_flips']]\n",
435 "test_data.extend(random.sample(test_flips['fudged'], k=random.randint(50, 70)))\n",
436 "test_data.extend(random.sample(test_flips['padding'], k=(99-len(test_data))))\n",
442 "execution_count": 23,
446 "random.shuffle(test_data)"
451 "execution_count": 24,
460 "execution_count": 24,
462 "output_type": "execute_result"
466 "sum(1 for f in test_data\n",
467 " if unburnt_sorted(\n",
468 " enflip(test_flips['pancakes'], f, burnt=False)))"
473 "execution_count": 25,
482 "execution_count": 25,
484 "output_type": "execute_result"
488 "sum(1 for f in test_data\n",
489 " if burnt_sorted(\n",
490 " enflip(test_flips['pancakes'], f, burnt=True)))"
495 "execution_count": 26,
504 "execution_count": 26,
506 "output_type": "execute_result"
510 "[i+1 for i, f in enumerate(test_data)\n",
511 " if burnt_sorted(\n",
512 " enflip(test_flips['pancakes'], f, burnt=True))]"
517 "execution_count": 27,
521 "# random.shuffle(test_data)\n",
522 "# with open('07-flips.txt', 'w') as tdf:\n",
523 "# tdf.write('burgers: {}\\n'.format(' '.join(str(i) for i in test_flips['pancakes'] if i > 0)))\n",
524 "# for i, c in enumerate(test_data):\n",
525 "# tdf.write('{:02}: {}\\n'.format(i+1, ' '.join(str(i) for i in c if i > 0)))"
530 "execution_count": null,
536 "cell_type": "markdown",
544 "execution_count": 28,
550 "{'burnt_flips': [5, 6, 2, 1, 2, 5, 3, 2, 3, 2, 3, 2],\n",
551 " 'pancakes': [8, 7, 5, 4, 11, 9],\n",
552 " 'fudged': [[5, 6, 1, 5, 4, 3, 4, 3, 4, 3, 4, 3],\n",
553 " [5, 6, 1, 5, 4, 3, 4, 3, 4, 3, 4, 3],\n",
554 " [5, 6, 2, 1, 2, 5],\n",
556 " [5, 6, 1, 5, 4, 3, 4, 3, 4, 3, 4, 3]],\n",
557 " 'padding': [[1, 6, 5],\n",
558 " [5, 6, 1, 4, 1, 2],\n",
559 " [1, 6, 5, 0, 4, 5, 2, 4, 2, 1, 2, 1],\n",
560 " [2, 6, 2, 5, 2, 3, 1, 2],\n",
561 " [2, 6, 4, 0, 1, 4, 1, 3, 1, 2]]}"
564 "execution_count": 28,
566 "output_type": "execute_result"
572 "fudge_rate = 0.7\n",
574 "start = [i for i in random.sample(list(range(1, ln+1)), k=ln)]\n",
576 "_, test_flips['burnt_flips'] = burnt_pancake_sort(start)\n",
577 "test_flips['pancakes'] = equiv_case(start, test_flips['burnt_flips'], burnt=True, max_value=ln*2)\n",
578 "test_flips['fudged'] = [burnt_pancake_sort(start, fudge_rate=fudge_rate)[1] for _ in range(n_equivs)]\n",
579 "test_flips['padding'] = [burnt_pancake_sort(random.sample(list(range(1, ln+1)), k=ln), fudge_rate=fudge_rate)[1] for _ in range(n_equivs)]\n",
585 "execution_count": 29,
589 "# test_flips = {'burnt_flips': [4, 5, 2, 1, 2, 3, 1],\n",
590 "# 'fudged': [[4, 5, 2, 1, 2, 3],\n",
591 "# [4, 5, 1, 3, 2, 1, 2, 1],\n",
592 "# [4, 5, 1, 3, 2, 1, 2, 1],\n",
594 "# [4, 5, 2, 1, 2, 3, 1]],\n",
595 "# 'padding': [[2, 5, 1, 2],\n",
596 "# [2, 5, 2, 1, 3],\n",
597 "# [1, 3, 1, 2, 1],\n",
598 "# [2, 5, 4, 1, 2, 3],\n",
599 "# [4, 5, 3, 4, 3, 1]],\n",
600 "# 'pancakes': [4, 2, 6, 7, 5]}"
605 "execution_count": 30,
609 "test_flips = {'burnt_flips': [3, 5, 3, 2, 3, 2],\n",
610 " 'pancakes': [9, 18, 22, 15, 13],\n",
611 " 'fudged': [[3, 5, 2, 3],\n",
616 " 'padding': [[4, 5, 3, 4, 2, 3],\n",
618 " [3, 5, 4, 2, 3, 4, 2],\n",
619 " [2, 5, 2, 3, 2],\n",
625 "execution_count": 31,
634 "execution_count": 31,
636 "output_type": "execute_result"
640 "bf = [f for f in test_flips['burnt_flips'] if f > 0]\n",
646 "execution_count": 32,
652 "[9, 13, 15, 18, 22]"
655 "execution_count": 32,
657 "output_type": "execute_result"
661 "enflip(test_flips['pancakes'], test_flips['burnt_flips'], burnt=True)"
666 "execution_count": 33,
672 "[-9, -13, -15, 18, 22]"
675 "execution_count": 33,
677 "output_type": "execute_result"
681 "enflip(test_flips['pancakes'], test_flips['fudged'][0], burnt=True)"
686 "execution_count": 34,
692 "[9, 13, 15, 18, 22]"
695 "execution_count": 34,
697 "output_type": "execute_result"
701 "enflip(test_flips['pancakes'], bf, burnt=True)"
706 "execution_count": 35,
711 "output_type": "stream",
713 " 9 22 13 9 15 13 9 \n",
714 "18 18 15 15 9 9 13 \n",
715 "22 -3-> 9 -5-> 9 -3-> 13 -2-> 13 -3-> 15 -2-> 15 \n",
716 "15 15 18 18 18 18 18 \n",
717 "13 13 22 22 22 22 22 \n"
722 "show_cached_flips(cache_flips(test_flips['pancakes'], bf))"
727 "execution_count": 36,
732 "output_type": "stream",
743 "show_cached_flips(cache_flips(test_flips['pancakes'], bf)[:1])"
748 "execution_count": 37,
753 "output_type": "stream",
764 "show_cached_flips(cache_flips(test_flips['pancakes'], bf)[:2])"
769 "execution_count": 38,
774 "output_type": "stream",
776 " 9 22* 13* 9* 15* 13* 9 \n",
777 "18 18* 15* 15 9 9* 13 \n",
778 "22 -3-> 9* -5-> 9 -3-> 13 -2-> 13 -3-> 15 -2-> 15 \n",
779 "15 15 18 18 18 18 18 \n",
780 "13 13 22 22 22 22 22 \n"
785 "show_cached_flips(cache_flips(test_flips['pancakes'], bf, burnt=True))"
790 "execution_count": 39,
795 "output_type": "stream",
806 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][0], burnt=False)[:1])"
811 "execution_count": 40,
816 "output_type": "stream",
827 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][0], burnt=False)[:2])"
832 "execution_count": 41,
837 "output_type": "stream",
841 "22 -3-> 9 -5-> 9 -2-> 9 -3-> 15 \n",
848 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][0], burnt=False))"
853 "execution_count": 42,
858 "output_type": "stream",
860 " 9 22* 13* 15 9*\n",
861 "18 18* 15* 13 13*\n",
862 "22 -3-> 9* -5-> 9 -2-> 9 -3-> 15*\n",
869 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][0], burnt=True))"
874 "execution_count": 43,
879 "output_type": "stream",
881 " 9 22* 13* 15 9*\n",
882 "18 18* 15* 13 13*\n",
883 "22 -3-> 9* -5-> 9 -2-> 9 -3-> 15*\n",
890 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][1], burnt=True))"
895 "execution_count": 44,
900 "output_type": "stream",
904 "22 -3-> 9 -5-> 9 -2-> 9 -3-> 15 \n",
911 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][3], burnt=False))"
916 "execution_count": 45,
921 "output_type": "stream",
923 " 9 22* 13* 15 9*\n",
924 "18 18* 15* 13 13*\n",
925 "22 -3-> 9* -5-> 9 -2-> 9 -3-> 15*\n",
932 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['fudged'][3], burnt=True))"
937 "execution_count": 46,
942 "output_type": "stream",
944 " 9 15 13 18 22 13 9 \n",
945 "18 22 9 9 13 22 22 \n",
946 "22 -4-> 18 -5-> 18 -3-> 13 -4-> 9 -2-> 9 -3-> 13 \n",
947 "15 9 22 22 18 18 18 \n",
948 "13 13 15 15 15 15 15 \n"
953 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['padding'][0]))"
958 "execution_count": 47,
963 "output_type": "stream",
965 " 9 18 13 15 22 13 \n",
966 "18 9 15 13 13 22 \n",
967 "22 -2-> 22 -5-> 22 -2-> 22 -3-> 15 -2-> 15 \n",
969 "13 13 18 18 18 18 \n"
974 "show_cached_flips(cache_flips(test_flips['pancakes'], test_flips['padding'][3]))"
979 "execution_count": 48,
988 "execution_count": 48,
990 "output_type": "execute_result"
994 "example_data = [test_flips['burnt_flips']]\n",
995 "example_data.extend(random.sample(test_flips['fudged'], k=4))\n",
996 "example_data.extend(random.sample(test_flips['padding'], k=5))\n",
1001 "cell_type": "code",
1002 "execution_count": 49,
1006 "random.shuffle(example_data)\n",
1007 "with open('07-example.txt', 'w') as tdf:\n",
1008 " tdf.write('burgers: {}\\n'.format(' '.join(str(i) for i in test_flips['pancakes'] if i > 0)))\n",
1009 " for i, c in enumerate(example_data):\n",
1010 " tdf.write('{:02}: {}\\n'.format(i+1, ' '.join(str(i) for i in c if i > 0)))"
1014 "cell_type": "code",
1015 "execution_count": null,
1023 "display_name": "Python 3",
1024 "language": "python",
1028 "codemirror_mode": {
1032 "file_extension": ".py",
1033 "mimetype": "text/x-python",
1035 "nbconvert_exporter": "python",
1036 "pygments_lexer": "ipython3",