forked from AC6567/geraldanekwe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutationStep.js
More file actions
77 lines (50 loc) · 1.22 KB
/
permutationStep.js
File metadata and controls
77 lines (50 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
var assertEqual = function(actual, expected){
console.log(actual === expected ? 'PASS' : 'FAIL');
};
function PermutationStep(num) {
var permArr = [],
usedChars = [];
var numJoinArr = [];
var answer = 0;
function permute(input) {
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length === 0) {
permArr.push(usedChars.slice());
}
permute(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr;
}
var numArr = num.toString().split("");
permute(numArr);
for(var i = 0; i < permArr.length; i++){
var newNum = Number(permArr[i].join(""));
numJoinArr.push(newNum);
}
function sortNum(cur, next){
return cur - next;
}
numJoinArr = numJoinArr.sort(sortNum);
for(j = 0; j < numJoinArr.length; j++){
if(num === numJoinArr[j]){
answer = numJoinArr[j + 1];
}
}
if(answer > num){
num = answer;
}
else{
num = -1;
}
return num;
}
assertEqual(PermutationStep(123), 132);
assertEqual(PermutationStep(12453), 12534);
assertEqual(PermutationStep(999), -1);
assertEqual(PermutationStep(11121), 11211);
assertEqual(PermutationStep(41352), 41523);