CMU Coding Bootcamp

feat: oct 2 level 4+

additional solution for route cipher

thecoded.prof 2ab905d9 747265f0

verified
Changed files
+66
python
oct2
+66
python/oct2/level4/routeCipher2.py
··· 1 + from math import ceil 2 + 3 + 4 + def f(row: int, col: int, rows: int) -> int: 5 + return col*rows + row 6 + 7 + 8 + def i_f(x: int, rows: int) -> tuple[int, int]: 9 + return x // rows, x % rows 10 + 11 + 12 + def encodeRouteCipher(message: str, rows: int) -> str: 13 + cur_char = "z" 14 + row_len = ceil(len(message) / rows) 15 + while len(message) % rows != 0: 16 + message += cur_char 17 + cur_char = chr(ord(cur_char) - 1) 18 + encoded_string = "" 19 + for i in range(len(message)): 20 + row, col = i_f(i, row_len) 21 + encoded_string += message[f(row, col, rows)] 22 + encoded_message = f"{rows}" 23 + for i in range(0, rows): 24 + if i % 2 == 0: 25 + encoded_message += encoded_string[i*row_len:(i+1)*row_len] 26 + else: 27 + encoded_message += encoded_string[i*row_len:(i+1)*row_len][::-1] 28 + return encoded_message 29 + 30 + 31 + def decodeRouteCipher(encodedMessage: str) -> str: 32 + decoded_message = "" 33 + rows = int(encodedMessage[0]) 34 + encoded_string = encodedMessage[1:] 35 + row_len = ceil(len(encoded_string) / rows) 36 + decoded_string = "" 37 + for i in range(rows): 38 + if i % 2 == 0: 39 + decoded_string += encoded_string[i*row_len:(i+1)*row_len] 40 + else: 41 + decoded_string += encoded_string[i*row_len:(i+1)*row_len][::-1] 42 + for i in range(len(decoded_string)): 43 + row, col = i_f(i, rows) 44 + decoded_message += decoded_string[f(row, col, row_len)] 45 + while decoded_message[-1].islower(): 46 + decoded_message = decoded_message[:-1] 47 + return decoded_message 48 + 49 + 50 + print("Testing encodeRouteCipher()...", end="") 51 + assert encodeRouteCipher("ASECRETMESSAGE", 4) == "4AREGESESETSzyAMC" 52 + assert encodeRouteCipher("ASECRETMESSAGE", 3) == "3ACTSGESMRSEEEAz" 53 + assert encodeRouteCipher("ASECRETMESSAGE", 5) == "5AESATSEMGEECRSz" 54 + assert encodeRouteCipher("ANOTHERSECRET", 4) == "4AHETzCENORRyxEST" 55 + 56 + 57 + print("Testing decodeRouteCipher()...", end="") 58 + assert decodeRouteCipher("4AREGESESETSzyAMC") == "ASECRETMESSAGE" 59 + assert decodeRouteCipher("3ACTSGESMRSEEEAz") == "ASECRETMESSAGE" 60 + assert decodeRouteCipher("5AESATSEMGEECRSz") == "ASECRETMESSAGE" 61 + assert decodeRouteCipher("4AHETzCENORRyxEST") == "ANOTHERSECRET" 62 + message = "SECRETSTUFFGOESHERE" 63 + encodedMessage = encodeRouteCipher(message, 6) 64 + plaintext = decodeRouteCipher(encodedMessage) 65 + assert plaintext == message 66 + print("Passed!")