permutation need help to code

2019-07-21 20:35发布

Thank for your reply, first thing i wish to thank you for trying to help me out, and i have post this in few website also no one trying to help at all.

For my code, what i wish to do is permutation count.

it will count from top to bottom
1,2,3
1,2,3
1,2,3

output to
111 = 1
112 = 1
113 = 1
121 = 1
122 = 1
123 = 1
133 = 1
211 = 1
212 = 1
213 = 1
333 = 1

and continue till all number is count and also store to the array which can check how many count after all

code will check the input number and count how many outcome and show the results with how many outcome and each have how many after permutation count.

Its hard to do?.

Anyway thank you for help.

1条回答
淡お忘
2楼-- · 2019-07-21 20:44

It's not that hard, I guess. It's just the standard permutation thing. You'll need to use a little recursion:

function permute(size) {
    var range = getRange(size);
    var result = [];
    getSubPerms('', range, result);
    return result;
};

function getRange(size) {
    var range = [];
    for (var i = 0; i < size; i++) {
        range.push(i + 1);
    }
    return range;
}

function getSubPerms(perm, range, result) {
    for (var i = 0; i < range.length; i++) {
        var perm2 = perm + range[i];
        if (perm2.length == range.length) {
            result.push(perm2);
        } else {
            getSubPerms(perm2, range, result);
        }
    }
}

var foo = permute(4); //an array of all of your results.
alert(foo.length); //256

However, if you're only interested in the length of that, without having to generate the results, it would simply be Math.pow(size, size) to get the length of your results.

查看更多
登录 后发表回答