# javascript - Java permutation algorithm

1.6k views

### 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?

``````<!DOCTYPE HTML>

<html>
<!--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>
<body>
<!--Script Result-->
<script type="text/javascript">
document.write(result);
</script>

</body>
</html>
``````

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.