DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #254 - The Vowel Code

Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:

a -> 1
e -> 2
i -> 3
o -> 4
u -> 5
For example, encode("hello") would return "h2ll4". There is no need to worry about uppercase letters for this challenge.

Step 2: Now create a function called decode() to turn the numbers back into vowels according to the same pattern shown above. For the sake of simplicity, you can assume that any numbers passed into the function will correspond to vowels.

For example, decode("h3 th2r2") would return "hi there".

Tests
decode('h2ll4'), 'hello')
encode('This is an encoding test.')
encode('How are you today?')
encode('This is an encoding test.')

Good luck!


This challenge comes from yaphi1 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!

Top comments (10)

Collapse
 
willsmart profile image
willsmart • Edited

Let's do it in JS using neat little generic HOF...

const
    codeFunctionForMapping = replacementMapping => (
      inputString => inputString.replace(/./g, c => replacementMapping[c] || c)
    ),
    encode = codeFunctionForMapping({a:1, e:2, i:3, o:4, u:5}),
    decode = codeFunctionForMapping({1:'a', 2:'e', 3:'i', 4:'o', 5:'u'})

Bit of a sanity check:

> encode('hello')
< "h2ll4"

> decode('h2ll4')
< "hello"

> encode('Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:')
< "St2p 1: Cr21t2 1 f5nct34n c1ll2d 2nc4d2() t4 r2pl1c2 1ll th2 l4w2rc1s2 v4w2ls 3n 1 g3v2n str3ng w3th n5mb2rs 1cc4rd3ng t4 th2 f4ll4w3ng p1tt2rn:"

> decode('St2p 1: Cr21t2 1 f5nct34n c1ll2d 2nc4d2() t4 r2pl1c2 1ll th2 l4w2rc1s2 v4w2ls 3n 1 g3v2n str3ng w3th n5mb2rs 1cc4rd3ng t4 th2 f4ll4w3ng p1tt2rn:')
< "Step a: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:" 
    // Well, I prefer alpha bullets anyway :|

Edit: inputString => inputString.replace(/./g, c => replacementMapping[c] ?? c) is a less supported but better choice -- caniuse.com/#search=%3F%3F

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Very nice

Collapse
 
willsmart profile image
willsmart

Cheers

Collapse
 
qm3ster profile image
Mihail Malo • Edited

JavaScript

normal (aka filthy coercion)

const letters = ['a', 'e' ,'i', 'o', 'u']
const letters_ex = /a|e|i|o|u/g
const numbers_ex = /[1-5]/g
// dirty coercion
const encode = str => str.replace(letters_ex, c => letters.indexOf(c) + 1)
const decode = str => str.replace(numbers_ex, c => letters[/*parseInt*/(c) - 1])

sneaky

const letters = [/*undefined*/, 'a', 'e' ,'i', 'o', 'u']
const letters_ex = /a|e|i|o|u/g
const numbers_ex = /[1-5]/g

const encode = str => str.replace(letters_ex, c => letters.indexOf(c))
const decode = str => str.replace(numbers_ex, c => letters[c]) // oh yes, real life string indexing

generic

const maek = (...letters) => {
  const len = letters.length;
  if (len < 1 || len > 9) throw "💩"
  const letters_ex = new RegExp(letters.join('|'), 'g')
  const numbers_ex =  new RegExp(`[1-${letters.length}]`, 'g')
  const l = [, ...letters]
  const encode = str => str.replace(letters_ex, c => l.indexOf(c))
  const decode = str => str.replace(numbers_ex, c => l[c])
  return {encode, decode}
}

const {encode, decode} = maek('a', 'e' ,'i', 'o', 'u')
Collapse
 
jpantunes profile image
JP Antunes • Edited

Easy JS solution.

const vowels = ['a', 'e' ,'i', 'o', 'u'];
const v4w2ls = ['1', '2', '3', '4', '5']; 

const encode = str => [...str].map(e => vowels.includes(e) ? e = vowels.indexOf(e) + 1 : e).join('');
const decode = str => [...str].map(e => v4w2ls.includes(e) ? e = vowels[v4w2ls.indexOf(e)] : e).join('');
Collapse
 
quoll profile image
Paula Gearon

A symmetric solution is probably better, but indexing letters but a number just called out to me for an array, even if the characters need to be converted to numbers to do so...

(def e {\a 1 \e 2 \i 3 \o 4 \u 5})
(def d [\a\e\i\o\u])

(defn encode [s] (apply str (map #(get e % %) s)))
(defn decode [s] (apply str (map #(get d (- (int %) (int \1)) %) s)))
Collapse
 
awwsmm profile image
Andrew (he/him)

A nice, simple, symmetric solution in Scala:

val toIndex = Map('a' -> '1', 'e' -> '2', 'i' -> '3', 'o' -> '4', 'u' -> '5')
val toVowel = toIndex map { _.swap }

def encode (str: String): String = str.map(ch => if (toIndex.contains(ch)) toIndex(ch) else ch).mkString
def decode (str: String): String = str.map(ch => if (toVowel.contains(ch)) toVowel(ch) else ch).mkString

Tests:

scala> decode("h2ll4")
res2: String = hello

scala> encode("hello")
res3: String = h2ll4

scala> decode("h3 th2r2")
res4: String = hi there

scala> decode("h2ll4")
res5: String = hello

scala> encode("This is an encoding test.")
res6: String = Th3s 3s 1n 2nc4d3ng t2st.

scala> encode("How are you today?")
res7: String = H4w 1r2 y45 t4d1y?
Collapse
 
peter279k profile image
peter279k

Here is my simple solution with Python:

def encode(st):
    encode_list = {
        'a': '1',
        'e': '2',
        'i': '3',
        'o': '4',
        'u': '5',
    }

    encoded_string = ""
    for char in st:
        if char in encode_list:
            encoded_string += encode_list[char]
        else:
            encoded_string += char

    return encoded_string

def decode(st):
    decode_list = {
        '1': 'a',
        '2': 'e',
        '3': 'i',
        '4': 'o',
        '5': 'u',
    }

    decoded_string = ""
    for char in st:
        if char in decode_list:
            decoded_string += decode_list[char]
        else:
            decoded_string += char

    return decoded_string
Collapse
 
pedrohasantiago profile image
Pedro S

My Python solution:

def encode(st):
    vowel_to_num = {'a': '1', 'e': '2', 'i': '3', 'o': '4', 'u': '5'}
    return ''.join(vowel_to_num.get(char, char) for char in st)

def decode(st):
    num_to_vowel = {'1': 'a', '2': 'e', '3': 'i', '4': 'o', '5': 'u'}
    return ''.join(num_to_vowel.get(char, char) for char in st)

After submitting this to Kata, I learned about the str.translate() method, which would make this much simpler 🧐

Collapse
 
thomasledoux1 profile image
Thomas Ledoux • Edited

My Javascript solution:

var vowels = ['a', 'e', 'i', 'o', 'u'];

function encode(input) {
  return [...input].map(char => vowels.includes(char) ? vowels.indexOf(char)+1 : char).join('');
}

function decode(input) {
  return [...input].map(char => Number(char) ? vowels[Number(char)-1] : char).join('');
}