Salutations.
I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.
For this next exercise we have an ordered, ascending array of letters, but somewhere in the middle one letter is missing:
['a','b','c','d','f']
['O','Q','R','S']
First, we need to know that letters have a corresponding numerical value in Unicode. Therefore, we need functions capable of transforming letters to numbers and vice versa.
Let's try some JS functions to see what they do:
function findMissingLetter(array)
{
return [array[3].charCodeAt(),array[4].charCodeAt()];
}
// the array is ['a','b','c','d','f']
// it expects 'e'
// this function returns [ 100, 102 ]
We have our first important piece of the puzzle. Now we need to create a solution around it. To do so, we could use something to traverse the array, looking for the anomaly:
let counter = 0;
while (array[counter].charCodeAt() + 1 == array[counter + 1].charCodeAt()
&& counter < array.length)
{
counter++;
}
Then, we need to find the actual missing letter:
let letter = String.fromCharCode(array[counter].charCodeAt() + 1)
Assemble everything:
function findMissingLetter(array)
{
let counter = 0;
while (array[counter].charCodeAt() + 1 == array[counter + 1].charCodeAt()
&& counter < array.length)
{
counter++;
}
let letter = String.fromCharCode(array[counter].charCodeAt() + 1)
return letter;
}
Surprisingly readable. I think it's fine. There has to be a way to optimize it, but I can't see how yet.
Take care. Drink water 💧💧💧.
Top comments (0)