Last active
September 28, 2016 19:16
-
-
Save pimiento/3a7a87d8e25a9b3cb0dd1d454ca4c5b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| check_results = { | |
| 5: """ | |
| 1 2 3 4 5 | |
| 16 17 18 19 6 | |
| 15 24 25 20 7 | |
| 14 23 22 21 8 | |
| 13 12 11 10 9""", | |
| 7: """ | |
| 1 2 3 4 5 6 7 | |
| 24 25 26 27 28 29 8 | |
| 23 40 41 42 43 30 9 | |
| 22 39 48 49 44 31 10 | |
| 21 38 47 46 45 32 11 | |
| 20 37 36 35 34 33 12 | |
| 19 18 17 16 15 14 13 """, | |
| 3: """ | |
| 1 2 3 | |
| 8 9 4 | |
| 7 6 5 """ | |
| } | |
| def numerator(n): | |
| threshold = n | |
| turn = 0 | |
| second_pass = True | |
| step = 1 | |
| yield 0 | |
| s_i, s_j = [0, 0] | |
| for x in range(n**2 - 1): | |
| s_i, s_j = { | |
| 0: [s_i, s_j + 1], # right | |
| 1: [s_i + 1, s_j], # down | |
| 2: [s_i, s_j - 1], # left | |
| 3: [s_i - 1, s_j] # up | |
| }[turn] | |
| yield (s_i * n) + s_j | |
| step += 1 | |
| if step == threshold: | |
| turn = (turn + 1) % 4 | |
| if second_pass: | |
| threshold -= 1 | |
| second_pass = not second_pass | |
| step = 0 | |
| def generate(n): | |
| num = 1 | |
| l = [None] * (n**2) | |
| for idx in numerator(n): | |
| l[idx] = str(num) | |
| num += 1 | |
| return '\n'.join(' '.join(l[x:x+n]) for x in range(0, len(l), n)) | |
| def check(n): | |
| result = generate(n, l) | |
| print("DONE" if result == check_results[n].strip() else "FAIL:\n%s\n" % result) | |
| if __name__ == "__main__": | |
| check(5) | |
| check(3) | |
| check(7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment