-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.permutation.next.js
More file actions
46 lines (40 loc) · 1.03 KB
/
string.permutation.next.js
File metadata and controls
46 lines (40 loc) · 1.03 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
/*
* @title: Permutations of String
* @description: Implement next permutation, which rearranges
* numbers into the lexicographically next greater permutation of numbers.
* If such arrangement is not possible, it must rearrange it as the
* lowest possible order (ie, sorted in ascending order).
* @author: Thorsten Kober
* @email: [email protected]
*/
function swap(arr, left, right) {
const temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
function reverse(arr, left, right) {
while (left < right) {
swap(arr, left, right);
left++;
right--;
}
}
function nextPermutation(arr) {
let i = arr.length - 2;
while (i >= 0 && arr[i + 1] <= arr[i]) {
i--;
}
if (i >= 0) {
let j = arr.length - 1;
while (j >= 0 && arr[j] <= arr[i]) {
j--;
}
swap(arr, i, j);
}
reverse(arr, i + 1, arr.length - 1);
return arr;
}
// npx jest algorithms/string/string.permutation.next.js
test('test next permutation', () => {
expect(nextPermutation([1, 2, 3])).toEqual([1, 3, 2]);
});