Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created August 7, 2014 14:57
Show Gist options
  • Save jikeytang/4476f26bf68cb43ac2eb to your computer and use it in GitHub Desktop.
Save jikeytang/4476f26bf68cb43ac2eb to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140808-题目1
请输出几个字母的所有可能的组合?
比如:a b c d e f g h i j k l,
ab, abce, acef等等。
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@replace5
Copy link

replace5 commented Aug 8, 2014

function log() {
    var i = 0,
        str = '',
        args = [].slice.call(arguments);

    j++;
    if (isRepeat(args)) {
        k++;
        return;
    }

    while(i < args.length) {
        str += chars[args[i]];
        i++;
    }
    console.log(str);
}

function count(obj) {
    var i = 0;
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            i++;
        }
    }
    return i;
}
function isRepeat(arr) {
    var i = 0,
        obj = {};
    while(i < arr.length) {
        obj[typeof arr[i] + arr[i]] = 1;
        if (count(obj) === i) {
            return true;
        }
        i++;
    }

    return false;
}
function loop(min, max, fn, count) {
    var i, args;
    i = min;
    count++;
    args = [].slice.call(arguments, 0);

    while(i < max) {
        var iargs = args.slice(0);
        iargs.push(i);

        fn.apply(window, iargs.slice(4));

        if (count < max - min) {
            arguments.callee.apply(window, iargs);
        }

        i++;
    }
}

var chars = ['a', 'b', 'c', 'd', 'e', 'f'];

var j = 0, k = 0;
loop(0, chars.length, log, 0);
console.log('共执行', j, '次, 不允许单字符重用有', j - k, '次, 允许单字符重用有', k, '次');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment