DEV Community

dev.to staff
dev.to staff

Posted on

7

Daily Challenge #235 - Reversing a Process

Suppose we know the process A by which a string s has been coded to a string r.

Implement a function that will decode r to get back the original string s.

Explanation of the known process A:
data: a string s composed of lowercase letters from a to z and a positive integer num
we know there is a correspondence between abcde...uvwxyz and 0, 1, 2 ..., 23, 24, 25 : 0 <-> a, 1 <-> b ...
If c is a character of s whose corresponding number is x, apply to x the function f: x-> f(x) = num * x % 26, then find ch the corresponding character of f(x).
Accumulate all these ch in a string r.
concatenate num and r and return the result.

code("mer", 6015) -> "6015ekx"
m <-> 12, 12 * 6015 % 26 == 4, 4 <-> e
e <-> 4, 4 * 6015 % 26 == 10, 10 <-> k
r <-> 17, 17 * 6015 % 26 == 23, 23 <-> x
We get "ekx" so the answer is: "6015ekx"

Task
A string s has been coded to a string r by the above process (A). Write a function decode(r) to get back s whenever it is possible.

Indeed it can happen that the decoding is impossible when positive integer num has not been correctly chosen. In that case return "Impossible to decode".

Example:
decode("6015ekx") -> "mer"
decode("5057aan") -> "Impossible to decode"

Tests:
decode("1273409kuqhkoynvvknsdwljantzkpnmfgf")
decode("761328qockcouoqmoayqwmkkic")

Good luck!


This challenge comes from g964 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
_bkeren profile image
'' • Edited

"Not correcly chosen" should be clarified.

ES6


  const alphabet = "abcdefghijklmnopqrstuvwxyz"

  const decode = (encoded) => {
    let number = parseInt(encoded.split(/\D/)[0])
    let text = encoded.substring(("" + number).length)
    let result = ""
    for(let i=0;i<text.length;i++) {
        let encodedIndex = alphabet.indexOf(text[i])
        for(let j=0;j<26;j++) {
            if((j*number - encodedIndex) % 26 === 0) {
                result += alphabet[j]
                break;
            }
        }
    }

    return result;
}

Collapse
 
avni999 profile image
Avni999

Looking this game cupcake-frenzy

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay