Java置换算法 [英] Java permutation algorithm

查看:24
本文介绍了Java置换算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我现在有了这个代码,在输入中我有我名字的字母ahimrsu"的升序.我需要从所有组合中显示正确的mariush"数字,应该是 2170.现在它只显示 ahimrsu、ahimrus、ahimsru、ahimsur、ahimurs、ahimusr、ahirmus、ahirmsu .... 等我该怎么办这个?

So I have this code now, and in input I have in ascending order my name's letters "ahimrsu". I need to show up the right number for "mariush" from all combinations which should to be 2170. For now it only show ahimrsu, ahimrus, ahimsru, ahimsur, ahimurs, ahimusr, ahirmus, ahirmsu.... etc How can I do this?

<!DOCTYPE HTML>

<html>
<head>
<!--Script Function Start Here-->
<script type="text/javascript">
        function perms(data) {
    if (!(data instanceof Array)) {
        throw new TypeError("input data must be an Array");
    }

    data = data.slice();  // make a copy
    var permutations = [],
        stack = [];

    function doPerm() {
        if (data.length == 0) {
            permutations.push(stack.slice());
        }
        for (var i = 0; i < data.length; i++) {
            var x = data.splice(i, 1);
            stack.push(x);
            doPerm();
            stack.pop();
            data.splice(i, 0, x);
        }
    }

    doPerm();
    return permutations;
}

var input = "ahimrsu".split('');
var result = perms(input);
for (var i = 0; i < result.length; i++) {
    result[i] = result[i].join('');
}
console.log(result);
</script>
<!--Header start here-->
</head>
<body>
<!--Script Result-->
<script type="text/javascript">
    document.write(result);
</script>

</body>
</html>

推荐答案

您的问题属于数学性质 - 组合和排列.您实际上是在询问字符串长度 7 的可能排列数.公式为阶乘(numOfchar).

Your question is of mathematics nature - combinations and permutations. You are actually asking the number of possible permutation for string length 7. The formula is factorial(numOfchar).

在这种情况下 7!= 7x6x5x4x3x2x1 = 5040.

public static void main(String[] args) {

    String str = "ABCDEFH";

    System.out.println("Number of permutations for " + str + " is : " + factorial(str.length()));
}


public static int factorial(int n)
{
    if (n == 0)
        return 1;

    int result = factorial(n-1)*n;
    return result;  
}

程序输出:

ABCDEFH 的排列数为:5040

既然你标记了 Java,这是你可以用 Java 完成它的一种方式.

Since you tagged Java, this is one way you can get the it done with Java.

这篇关于Java置换算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆