Skip to content

Commit 53e1579

Browse files
authored
V 0.5
1 parent 01b685e commit 53e1579

File tree

1 file changed

+37
-7
lines changed

1 file changed

+37
-7
lines changed

simple_encoder_decoder.py

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,23 +29,53 @@ def generate_charset(seed: int = 0):
2929
return ''.join(charset)
3030

3131

32-
def encode(text: str, charset: str, shift_pattern: list[int]) -> str:
32+
def get_random_charsets(charset: str, shift_pattern: list[int]) -> list:
33+
random_charsets = []
34+
for i in shift_pattern:
35+
rng = random.Random(i) # Local RNG instance
36+
new_charset = list(charset)
37+
rng.shuffle(new_charset)
38+
random_charsets.append(new_charset)
39+
return random_charsets
40+
41+
42+
def _code(text: str, charset: str, shift_pattern: list[int], encode: bool):
3343
result = ""
44+
45+
# generate a list of charsets
46+
random_charsets = get_random_charsets(charset, shift_pattern)
47+
48+
# Encode the text using the shift pattern
3449
pattern_length = len(shift_pattern)
3550
for i, char in enumerate(text):
3651
if char in charset:
37-
shift = shift_pattern[i % pattern_length]
38-
index = charset.index(char)
39-
result += charset[(index + shift) % len(charset)]
52+
i_shift = i % pattern_length
53+
shift = shift_pattern[i_shift]
54+
55+
random_charset: str = random_charsets[i_shift]
56+
57+
index = random_charset.index(char)
58+
59+
# Calculate the new index based on encoding or decoding
60+
offset : int
61+
if encode:
62+
offset = (index + shift) % len(random_charset)
63+
else:
64+
offset = (index - shift) % len(random_charset)
65+
66+
# Append the character from the random charset
67+
result += random_charset[offset]
4068
else:
4169
result += char
4270
return result
4371

4472

73+
def encode(text: str, charset: str, shift_pattern: list[int]) -> str:
74+
return _code(text, charset, shift_pattern, encode=True)
75+
76+
4577
def decode(text: str, charset: str, shift_pattern: list[int]) -> str:
46-
# Negate each shift to reverse the encoding
47-
reversed_pattern = [-s for s in shift_pattern]
48-
return encode(text, charset, reversed_pattern)
78+
return _code(text, charset, shift_pattern, encode=False)
4979

5080

5181
class EncoderDecoderUI():

0 commit comments

Comments
 (0)