[codewar]Filter unused digits 過濾沒有用過的數字

Description:

Given few numbers, you need to print out the digits that are not being used.javascript

Example:

unusedDigits(12, 34, 56, 78) // "09"
unusedDigits(2015, 8, 26) // "3479"

Note:

Result string should be sorted
The test case won't pass Integer with leading zerojava

我最初的解法:git

function unusedDigits() {
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var arguArray = arguments;
    var s = "";
    for (var i = 0; i < arguArray.length; i++) {
        var lalla = arguArray[i].toString();
        s += lalla;
    }
    for (var j = 0; j < s.length; j++) {
        for (var k = 0; k < arr.length; k++) {
            if (s.charAt(j) == arr[k].toString()) {
                arr.splice(k, 1);
            }
        }
    }
    return arr.join("");
}
unusedDigits(12, 34, 56, 78);

而後發現數組轉字符串沒有這麼麻煩,用join("")就能夠搞定,因而優化了一下變成數組

function unusedDigits() {
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var s=[].join.call(arguments,"");
    for (var j = 0; j < s.length; j++) {
        for (var k = 0; k < arr.length; k++) {
            if (s.charAt(j) == arr[k].toString()) {
                arr.splice(k, 1);
            }
        }
    }
    return arr.join("");
}
unusedDigits(12, 34, 56, 78);

而後我在其餘人的解法裏看到有好多map, forEach, filter, reduce等函數,以前一直也沒好好整理一下,如今藉此機會整理一下,方便之後回顧。
知乎上這篇寫的很好:https://www.zhihu.com/question/24927450
大概能歸納這幾個函數了
函數

大牛的解法:優化

function unusedDigits(...args){ return "0123456789".replace(new RegExp('['+args.join('')+']','g'), '')}

比較實際的寫法:spa

function unusedDigits() {
    return [].reduce.call(arguments, function (left, num) {
        (num + '').split('').map(function (digit) {
            left = left.replace(digit, '');
        });
        return left;
    }, '0123456789');
}
相關文章
相關標籤/搜索