Skip to content

Instantly share code, notes, and snippets.

@bruckhaus
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruckhaus/862d3fb7c384e2ff0a33 to your computer and use it in GitHub Desktop.
Save bruckhaus/862d3fb7c384e2ff0a33 to your computer and use it in GitHub Desktop.
class Pandigital:
def __init__(self, digits):
self.p = digits
self.N = len(self.p)
def find(self, n):
for i in range(n - 1):
self.step()
return self.get()
def step(self):
# The algorithm is described in E. W. Dijkstra, A Discipline of Programming, Prentice-Hall, 1997, p. 71
i = self.N - 1
while self.p[i-1] >= self.p[i]:
i -= 1
j = self.N
while self.p[j - 1] <= self.p[i - 1]:
j -= 1
self.swap(i-1, j-1) # swap values at positions (i-1) and (j-1)
i += 1
j = self.N
while i < j:
self.swap(i-1, j-1)
i += 1
j -= 1
def swap(self, i, j):
swap = self.p[j]
self.p[j] = self.p[i]
self.p[i] = swap
def next(self):
if not self.has_next():
return False
self.step()
return self.get()
def has_next(self):
for i in range(self.N - 1):
if self.p[i] < self.p[i + 1]:
return True
return False
def get(self):
return ''.join([str(d) for d in self.p])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment