Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

javascript - Java permutation algorithm

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?


<!--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) {
        for (var i = 0; i < data.length; i++) {
            var x = data.splice(i, 1);
            data.splice(i, 0, x);

    return permutations;

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

See Question&Answers more detail:os

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

In this case 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;  

Program Output:

Number of permutations for ABCDEFH is : 5040

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

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share