Home > Web Front-end > JS Tutorial > Codewars - Find the missing letter

Codewars - Find the missing letter

Linda Hamilton
Release: 2025-01-07 23:59:44
Original
921 people have browsed it

Salutations.

Codewars - Find the missing letter

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 ]
Copy after login

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++;
  }
Copy after login

Then, we need to find the actual missing letter:

let letter = String.fromCharCode(array[counter].charCodeAt() + 1)
Copy after login

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;
}
Copy after login

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 ???.

Previous

The above is the detailed content of Codewars - Find the missing letter. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template