Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2013 00:27
Show Gist options
  • Save anonymous/5596164 to your computer and use it in GitHub Desktop.
Save anonymous/5596164 to your computer and use it in GitHub Desktop.
# by aji, http://github.com/aji
# (couldn't be bothered to log into account at work)
import sys
alphabet = sys.argv[1]
length = int(sys.argv[2])
# yields every possible permutation of n elements of alphabet
def each(n=length):
if n == 0:
yield ''
return
for x in each(n-1):
for y in alphabet:
yield x + y
# yields every node adjacent to s in the graph
def adj(s):
for x in alphabet:
yield s[1:] + x
# find the first winning sequence of nodes
def dfs(seen, depth_want=None):
if depth_want is None:
depth_want = len(alphabet) ** len(seen[0])
if len(seen) == depth_want:
return seen
for n in adj(seen[-1]):
if n not in seen:
winner = dfs(seen + [n], depth_want)
if winner is not None:
return winner
return None
# invoke
winner = dfs([alphabet[0] * length])
s = ''.join([winner[0][:-1]] + [x[-1] for x in winner])
# output
print(s)
for x in each():
if x not in s:
print('alg missed ' + x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment