DEV Community

Discussion on: Daily Challenge #60 - Find the Missing Letter

Collapse
 
aminnairi profile image
Amin • Edited

My take at the challenge written in TypeScript this time and using a recursive solution!

"use strict";

type Letters = string[];
type LetterCode = number | undefined;
type MissingLetter = string | false;

function missingLetter(
    letters: Letters,
    nextLetterCode: LetterCode = undefined
): MissingLetter {
    if (letters.length === 0) {
        return false;
    }

    if (nextLetterCode === undefined) {
        nextLetterCode = letters[0].charCodeAt(0);
    }

    const [ letter, ...rest ]: Letters = letters;
    const letterCode: LetterCode = letter.charCodeAt(0);

    if (letterCode !== nextLetterCode) {
        return String.fromCharCode(letterCode - 1);
    }

    return missingLetter(rest, nextLetterCode + 1);
}

console.log(missingLetter(["a", "b", "c", "d", "f"])); // "e"
console.log(missingLetter(["O", "Q", "R", "S"])); // "P"
console.log(missingLetter(["a", "b", "c", "d", "e", "f"])); // false

I haven't done that much of a test so do not hesitate to tell me if I'm wrong. I also have returned false whether when there was no missing letters. I guess my solution will fail when the first letter is at the beginning or at the end of the array. The source-code with the playground is available here!

Collapse
 
aminnairi profile image
Amin • Edited

I also did use my algorithm in Elm. Here is the source-code for the inner logic function.

getMissingLetter : List Char -> Char -> Maybe Char
getMissingLetter letters nextCharacter =
    case letters of
        [] ->
            Nothing

        letter :: rest ->
            let
                characterCode =
                    Char.toCode letter

                nextCharacterCode =
                    Char.toCode nextCharacter
            in
            if characterCode /= nextCharacterCode then
                Just nextCharacter

            else
                getMissingLetter rest <| Char.fromCode <| nextCharacterCode + 1

I bet there could be a way to use it in Haskell or PureScript as well, but I'm more confortable using Elm for now.

And the testing is of course available here on Ellie App.