Word generator algorithm?

I am new to the site. would like to help if at all possible.

I need an algorithm that calculates a list of words after entering the available letters and word length. I am adding a Draw Something solution section to my site. I'm a web developer, extensive knowledge of XHTML, CSS and some JS, but that's about it, I don't think it can be done without using something more powerful like python or C ++?

+3


source to share


1 answer


In javascript executed in your browser:

vocabulary = ['start', 'tarts', 'stars', 'rats', 'tears']  // ...etc. read from a file

function letters(word) {
    return word.split('');
}

function possibleWords(length, allowedLetters) {
    var isAllowedLetter = function(letter) {
        return allowedLetters.indexOf(letter) != -1;  // allowedLetters contains letter
    };
    return vocabulary.filter(function(word) {
        return word.length==length && letters(word).every(isAllowedLetter);
    })
}

      

Demo:

> possibleWords(5, ['s','t','a','r'])
["start", "tarts", "stars"]

      

 




 

To make it more efficient, you would do:

vocabulary = ['start', 'tarts', 'stars', 'rats', 'tears']  // ...etc. read from a file

function letters(word) {
    return word.split('');
}

function set(iterable) {
    var data = {};
    iterable.forEach(function(x) {
        data[x] = true;
    });
    return {
        contains: function(x) {
            return !(data[x]===undefined);
        }
    };
}

function possibleWords(length, allowedLetters) {
    var isAllowedLetter = allowedLetters.contains;
    return vocabulary.filter(function(word) {
        return word.length==length && letters(word).every(isAllowedLetter);
    })
}

      

Demo:

> possibleWords(5, set(['s','t','a','r']))
["start", "tarts", "stars"]

      

+3


source







All Articles