This is the fifteenth puzzle in Matt Parker's Matt Parker's Maths Puzzles puzzle series
Find a permutation of the numbers 1 to 9 such that the sum of any two adjacent numbers is prime.
e.g. The permutation 9 8 7 6 5 4 3 2 1 does not satisfy the condition because 8 and 7 are adjacent and 8 + 7 = 15 = 3 * 5 which is not prime.
This seems like a great candidate for backtracking. In much the same way we would solve a sudoku with backtracking, we start with an empty permutation and attempt to add values onto the end, such that the permutation so far satisfies the condition that sums of adjacent terms are prime.
Here is an example of such a backtracking algorithm:
def allPrimePairPermutations(n):
"""
Returns all the permutations of 1 to n such that the sum of any pair of
adjacent numbers is prime.
"""
# Our resulting list of the valid permutations. This will be populated by
# the backtracking algorithm.
result = []
# A set to let us know whether we have used a value yet.
used = [False] * (n + 1)
# The largest sum of two adjacent numbers is n + (n - 1), so we don't need
# to know any primes larger than that.
primes = set(primesLessThan(2 * n))
# The permutation so far.
perm = []
# Our backtracking method.
def findPermutations():
if len(perm) == n:
# we have a valid permutation; we should add it to the result.
result.append(perm.copy())
return
# otherwise attempt to append an unused value to the current permutation
for cand in range(1, n + 1):
if used[cand]:
# we shouldn't use any number more than once
continue
if len(perm) == 0 or perm[-1] + cand in primes:
# If adding cand to our permutation preserves our condition, we
# should append it to our current permutation and recurse.
# The candidate number is now used.
used[cand] = True
perm.append(cand)
# We now recurse down.
findPermutations()
# We finished checking the permutations, we can pop our
# candidate from the permutation and continue the loop.
perm.pop()
used[cand] = False
# Start backtracking.
findPermutations()
return result
It turns out there are quite a few valid answers:
All 140 valid permutations
- 1, 2, 3, 4, 7, 6, 5, 8, 9
- 1, 2, 3, 4, 9, 8, 5, 6, 7
- 1, 2, 3, 8, 5, 6, 7, 4, 9
- 1, 2, 3, 8, 9, 4, 7, 6, 5
- 1, 2, 5, 6, 7, 4, 3, 8, 9
- 1, 2, 5, 6, 7, 4, 9, 8, 3
- 1, 2, 9, 4, 3, 8, 5, 6, 7
- 1, 2, 9, 4, 7, 6, 5, 8, 3
- 1, 2, 9, 8, 3, 4, 7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