Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kristopolous
Last active September 20, 2021 07:22
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 kristopolous/d7ac188507030f066e07307a3660cce5 to your computer and use it in GitHub Desktop.
Save kristopolous/d7ac188507030f066e07307a3660cce5 to your computer and use it in GitHub Desktop.
transposition die roll example
#!/usr/bin/env python3
import random
def encode(plain):
plain = list(plain)
cypher = ''
while len(plain) > 0:
# Roll a die, add 3 to the result
step = random.randint(4,9)
# start at the beginning of the remaining string
offset = 0
# Add the offset to step through the cypher
cypher += str(step)
# while there's remaining characters
while len(plain) > offset:
# take the x*step character
cypher += plain[offset]
# clear it out from our plaintext
plain[offset] = None
# and move forward
offset += step
# reduce our plaintext to remove those transposed characters
plain = list(filter(None, plain))
return cypher
def decode(cypher):
# start with an empty grid
plain = [None] * len(cypher)
for i in cypher:
# If we find a number then it's a transposition instruction
if i.isdigit():
step = int(i)
# reset all our pointers and go to the next character
pointer = 0
# we start at offset "0" of the first available slot each time
countdown = 0
continue
# We find the next available slot
# and make sure our destination slot is free
while countdown > 0 or plain[pointer] is not None:
if plain[pointer] is None:
countdown -= 1
pointer += 1
# putting our letter in place
plain[pointer] = i
# And start our counting again
countdown = step - 1
return ''.join( filter(None, plain) )
plain = 'Yea, though I walk through the valley of the shadow of death, I will fear no evil: for thou art with me; thy rod and thy staff they comfort me.'
cypher = encode(plain)
maybe = decode(cypher)
print("\n".join([plain, cypher, maybe]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment