Skip to content

Commit 1cc65e6

Browse files
committed
Add Generate Permutations backtracking algorithm
1 parent 2d59f57 commit 1cc65e6

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

Diff for: backtracking/GeneratePermutations.ts

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Problem Statement: Generate all distinct permutations of an array (all permutations should be in sorted order);
3+
*
4+
* What is permutations?
5+
* - Permutation means possible arrangements in a set (here it is an array);
6+
*
7+
* Reference to know more about permutations:
8+
* - https://www.britannica.com/science/permutation
9+
*
10+
*/
11+
12+
const swap = <T>(arr: T[], i: number, j: number): T[] => {
13+
const newArray: T[] = [...arr]
14+
15+
const temp: T = newArray[i]
16+
newArray[i] = newArray[j]
17+
newArray[j] = temp
18+
19+
return newArray
20+
}
21+
22+
const permutations = <T>(arr: T[]): T[][] => {
23+
const P: T[][] = []
24+
const permute = (arr: T[], low: number, high: number): T[][] => {
25+
if (low === high) {
26+
P.push([...arr])
27+
return P
28+
}
29+
for (let i = low; i <= high; i++) {
30+
arr = swap(arr, low, i)
31+
permute(arr, low + 1, high)
32+
}
33+
return P
34+
}
35+
return permute(arr, 0, arr.length - 1)
36+
}
37+
38+
export { permutations }

Diff for: backtracking/test/GeneratePermutations.test.ts

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { permutations } from '../GeneratePermutations'
2+
3+
const factorial = (n: number): number => {
4+
if (n === 0 || n === 1) {
5+
return 1
6+
}
7+
return n * factorial(n - 1)
8+
}
9+
10+
describe('Permutations', () => {
11+
it('Permutations of [a]', () => {
12+
const perms = permutations(['a'])
13+
expect(perms).toHaveLength(factorial(1))
14+
expect(perms).toContainEqual(['a'])
15+
})
16+
17+
it('Permutations of [true, false]', () => {
18+
const perms = permutations([true, false])
19+
expect(perms).toHaveLength(factorial(2))
20+
expect(perms).toContainEqual([true, false])
21+
expect(perms).toContainEqual([false, true])
22+
})
23+
24+
it('Permutations of [1, 2, 3]', () => {
25+
const perms = permutations([1, 2, 3])
26+
expect(perms).toHaveLength(factorial(3))
27+
expect(perms).toContainEqual([1, 2, 3])
28+
expect(perms).toContainEqual([1, 3, 2])
29+
expect(perms).toContainEqual([2, 1, 3])
30+
expect(perms).toContainEqual([2, 3, 1])
31+
expect(perms).toContainEqual([3, 1, 2])
32+
expect(perms).toContainEqual([3, 2, 1])
33+
})
34+
35+
it('Permutation counts across larger input arrays', () => {
36+
expect(permutations([1, 2, 3, 4, 5, 6, 7, 8])).toHaveLength(factorial(8))
37+
expect(permutations([1, 2, 3, 4, 5, 6, 7, 8, 9])).toHaveLength(factorial(9))
38+
})
39+
})

0 commit comments

Comments
 (0)