排列可以通过计数基数 3 列出。
算法(伪代码)
Start i=00000000 and end at 22222222 in base 3:
str_i = encode i in { &, *, % } character set
print str_i
i = i + 1 (in base 3)
代码示例(在 Python 中)
def main():
start = int('00000000', 3)
end = int('22222222', 3)
for i in range(start, end + 1):
# convert binary to base 3
perm_base3 = str_base(i, 3)
perm_charset = encode_to_charset(perm_base3)
print(perm_charset)
# custom character set
# & = 0
# * = 1
# % = 2
def encode_to_charset(str_number_base3):
ret = []
for c in str_number_base3:
if c == '0':
ret.append('&')
elif c == '1':
ret.append('*')
elif c == '2':
ret.append('%')
else:
pass #TODO handle error here
return "".join(ret)
#
# Utility functions
# https://stackoverflow.com/questions/2063425/python-elegant-inverse-function-of-intstring-base
#
def digit_to_char(digit):
if digit < 10: return chr(ord('0') + digit)
else: return chr(ord('a') + digit - 10)
def str_base(number,base):
if number < 0:
return '-' + str_base(-number,base)
else:
(d,m) = divmod(number,base)
if d:
return str_base(d,base) + digit_to_char(m)
else:
return digit_to_char(m)
main()
现场示例(在 repl.it 上)
https://repl.it/@KyleMarshall1/PermutationAlgorithm