Skip to content

Commit 09da5ee

Browse files
committed
Fix GeneratePermutations so that it actually returns the permutations instead of logging them + add Jest test.
1 parent 4f4deac commit 09da5ee

File tree

2 files changed

+31
-13
lines changed

2 files changed

+31
-13
lines changed

Backtracking/GeneratePermutations.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/*
2-
* Problem Statement: Generate all distinct permutations of a string/array (all permutations should be in sorted order);
2+
* Problem Statement: Generate all distinct permutations of a an array (all permutations should be in sorted order);
33
*
44
* What is permutations?
5-
* - Permutation means possible arrangements in a set (here it is string/array);
5+
* - Permutation means possible arrangements in a set (here it is an array);
66
*
77
* Reference to know more about permutations:
88
* - https://www.britannica.com/science/permutation
@@ -17,17 +17,21 @@ const swap = (arr, i, j) => {
1717
return newArray
1818
}
1919

20-
const permutations = (arr, low, high) => {
21-
if (low === high) {
22-
console.log(arr.join(' '))
23-
return
24-
}
25-
for (let i = low; i <= high; i++) {
26-
arr = swap(arr, low, i)
27-
permutations(arr, low + 1, high)
20+
const permutations = arr => {
21+
let P = []
22+
const permute = (arr, low, high) => {
23+
if (low === high) {
24+
P.push([...arr])
25+
// console.log(arr.join(' '))
26+
return P
27+
}
28+
for (let i = low; i <= high; i++) {
29+
arr = swap(arr, low, i)
30+
permute(arr, low + 1, high)
31+
}
32+
return P
2833
}
34+
return permute(arr, 0, arr.length - 1)
2935
}
3036

31-
// Driver Code
32-
const input = [1, 2, 3]
33-
permutations(input, 0, input.length - 1)
37+
export { permutations }
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { permutations } from '../GeneratePermutations'
2+
3+
describe('Permutations', () => {
4+
it('Permutations of [1, 2, 3]', () => {
5+
expect(permutations([1, 2, 3])).toEqual([
6+
[ 1, 2, 3 ],
7+
[ 1, 3, 2 ],
8+
[ 2, 1, 3 ],
9+
[ 2, 3, 1 ],
10+
[ 3, 1, 2 ],
11+
[ 3, 2, 1 ]
12+
])
13+
})
14+
})

0 commit comments

Comments
 (0)