Home >Web Front-end >JS Tutorial >JavaScript Fun Questions: Practical Combinations of Permutations

JavaScript Fun Questions: Practical Combinations of Permutations

黄舟
黄舟Original
2017-02-04 15:08:361365browse

First of all, let’s look at this picture, which is similar to the button desktop of the old phablet phone.

JavaScript Fun Questions: Practical Combinations of Permutations

If we press the "2" key, we can call up the three letters "A", "B", and "C".
In addition to the "1" and "0" keys, other numeric keys can call up a variety of letters.
Now the question is, if I select four arbitrary numeric keys, how many alphanumeric combinations can I get?
For example, I selected "0002", because the "0" key has no corresponding letter, so there are only three combinations of it - "000A", "000B", "000C".
Let's take a more complicated example. Press "0023" continuously, "0" remains unchanged, "2" can correspond to "A", "B", "C", "3" can correspond to "D", " E", "F", then, according to the knowledge of permutation and combination, there should be 1*1*3*3=9 combinations.
Okay, let’s see how to solve this problem.
The first step is to establish a mapping based on the relationship between numeric keys and corresponding letters.

var map = {  
    1 : [ 1 ],  
    2 : [ "A", "B", "C" ],  
    3 : [ "D", "E", "F" ],  
    4 : [ "G", "H", "I" ],  
    5 : [ "J", "K", "L" ],  
    6 : [ "M", "N", "O" ],  
    7 : [ "P", "Q", "R", "S" ],  
    8 : [ "T", "U", "V" ],  
    9 : [ "W", "X", "Y", "Z" ],  
    0 : [ 0 ]  
};

The second step is to use recursion to solve permutations and combinations

function telephoneWords(digitString) {  
    var array = [];  
    var result = [];  
    digitString.split("").forEach(function(e) {  
        array.push(map[e]);  
    })  
    var traverse = function foo(from, to) {  
        if (to.length < 4) {  
            var cur = from.shift();  
            for (var i = 0; i < cur.length; i++) {  
                var newTo = to.slice(0);  
                newTo.push(cur[i]);  
                var newFrom = from.slice(0);  
                foo(newFrom, newTo);  
            }  
        } else {  
            result.push(to.join(""));  
        }  
    };  
    traverse(array, []);  
    return result;  
}

The above is the content of JavaScript interesting questions: practical permutations and combinations. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Statement:
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