Created
November 8, 2021 02:59
-
-
Save htnminh/2e3aa7d82b87ca83111c7a5f41acc55c to your computer and use it in GitHub Desktop.
Generate permutations
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
class Permutation(): | |
def __init__(self, n): | |
self.n = n | |
self.a = [None] + [i for i in range(1, self.n+1)] | |
def __str__(self): | |
return ''.join([str(x) for x in self.a[1:]]) | |
def final(self): | |
return self.a == [None] + [i for i in range(self.n, 0, -1)] | |
def to_next(self): | |
j = self.n - 1 | |
while self.a[j] >= self.a[j+1]: | |
j -= 1 | |
min = None | |
saved_k = None | |
for k in range(j+1, self.n+1): | |
if self.a[k]>self.a[j] and (min is None or self.a[k]<min): | |
saved_k = k | |
self.a[j], self.a[saved_k] = self.a[saved_k], self.a[j] | |
self.a = [self.a[i] for i in range(j+1)] + \ | |
list(reversed([self.a[i] for i in range(j+1, self.n+1)])) | |
def generate(n=4): | |
curr_config = Permutation(n) | |
print(curr_config) | |
while True: | |
if not curr_config.final(): | |
curr_config.to_next() | |
print(curr_config) | |
else: | |
break | |
generate(n=4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment