Search code examples
javascriptpermutationalphabetical

Javascript function to generate list of all possible words that conform to vowel and consonant pattern


I am trying to create a function that will generate an array of all possible letter combinations that fit a pattern of vowels and consonants.

For example given the string "VCV" where V = vowel and C = consonant I want to get a list of all possible letter combinations that conform to that pattern.

['ABA', 'ABE', 'ABI', 'ABO', 'ABU', 'ACA', 'ACE', ....]

Any ideas?


Solution

  • If you want to just naively combine letters then that is one thing. However you seem to imply that you want to generate valid words, that is a whole different task.

    The basic steps would involve:

    • Deciding on a source for the words you would like to pull from

    • Tagging all of those words for vowels and consonants

    • Writing a way to access them / query them

    I think that doing all of this client side in the browser would be a bad idea, considering a dictionary of any size is going to take a less-than-insignificant amount of resources. I would recommend your JS send a request to a server, which serve that request, and then send back the results with something like AJAX.

    There are then a lot of things you could do server-side, although I have personally used NLTK for language tasks with great success, that might be a place to start.

    EDIT

    You made your question more clear. Assumning you have an array of vowels, vowels, and consonants, consonants, Maybe something like this:

    var results = []
    function getResult(refString, currentString){
        if(currentString === undefined){
            currentString = "";
        }
        if(refString.length === 0){
            return currentString;
        }else {
            if(refString[0] === 'C'){
                for(var i in consonants){
                     results.push(getResult(refString.slice(1),currentString + consonants[i]));
                }
            } else if (refString[0] === 'V'){
                for(var i in vowels){
                     results.push(getResult(refString.slice(1),currentString + vowels[i]));
                }
            }
        }
    }