Last active
September 23, 2023 14:36
-
-
Save Hermann-SW/19d429787d7f8e4cf43cd04e8345868e to your computer and use it in GitHub Desktop.
Find permutations of numbers 1..N with each successive pair summing to a square
This file contains 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
# pylint: disable=C0103, R1728 | |
# invalid-name, consider-using-generator | |
""" blacked and pylinted; https://mersenneforum.org/showthread.php?t=22915 """ | |
import sys | |
from sys import argv, stderr | |
from math import isqrt | |
N = 15 if len(argv) < 2 else int(argv[1]) | |
a = [[] for i in range(N + 1)] | |
stop = len(argv) >= 3 | |
def is_square(i): | |
"""silence pylint""" | |
return i == isqrt(i) ** 2 | |
def populate(A): | |
"""poulate adjacency list""" | |
for sq in range(2, 2 * N): | |
if is_square(sq): | |
for v in range(max(sq - N, 1), min(N + 1, sq)): | |
if v != sq - v: | |
A[v].append(sq - v) | |
def srch(A, seen, v, cnt, sol): | |
"""recursive search at nove v""" | |
seen[v] = True | |
cnt[0] += 1 | |
sol.append(v) | |
if cnt[0] == N: | |
print(sol) | |
if stop: | |
sys.exit() | |
else: | |
for w in A[v]: | |
if not seen[w]: | |
srch(A, seen, w, cnt, sol) | |
cnt[0] -= 1 | |
seen[v] = False | |
sol.pop() | |
populate(a) | |
print("average vertex degree:", sum([len(l) for l in a]) / N, file=stderr) | |
for s in range(N + 1): | |
if a[s] != []: | |
srch(a, [False for i in range(N + 1)], s, [0], []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://mersenneforum.org/showthread.php?p=638895#post638895