DEV Community

Discussion on: Daily Challenge #118 - Reversing a Process

Collapse
colorfusion profile image
Melvin Yeo

In python

import re

def decode(str):
    # check whether input string is valid
    if (first_digit := re.search(r"[a-zA-Z]", str)) is None:
        return "Impossible to decode"
    else:
        # extract the integer and text from string
        decode_num = int(str[0:first_digit.start()])
        text = str[first_digit.start():]

    result_str = ""

    # loop through all characters to decode string
    for char in text:
        index = ord(char) - ord('a')
        found = False
        # loop through all alphabets to decode string
        for num in range(0, 26):
            if num * decode_num % 26 == index:
                # if a character can be encoded in multiple alphabets, then it is impossible to decode
                if found:
                    return "Impossible to decode"
                else:
                    result_str += chr(ord('a') + num)
                    found = True

        if not found:
            return "Impossible to decode"

    return result_str


print(decode("6015ekx"))
print(decode("5057aan"))