mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Fix GeneratePermutations so that it actually returns the permutations instead of logging them + add Jest test.
This commit is contained in:
@ -1,8 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
* Problem Statement: Generate all distinct permutations of a string/array (all permutations should be in sorted order);
|
* Problem Statement: Generate all distinct permutations of a an array (all permutations should be in sorted order);
|
||||||
*
|
*
|
||||||
* What is permutations?
|
* What is permutations?
|
||||||
* - Permutation means possible arrangements in a set (here it is string/array);
|
* - Permutation means possible arrangements in a set (here it is an array);
|
||||||
*
|
*
|
||||||
* Reference to know more about permutations:
|
* Reference to know more about permutations:
|
||||||
* - https://www.britannica.com/science/permutation
|
* - https://www.britannica.com/science/permutation
|
||||||
@ -17,17 +17,21 @@ const swap = (arr, i, j) => {
|
|||||||
return newArray
|
return newArray
|
||||||
}
|
}
|
||||||
|
|
||||||
const permutations = (arr, low, high) => {
|
const permutations = arr => {
|
||||||
if (low === high) {
|
let P = []
|
||||||
console.log(arr.join(' '))
|
const permute = (arr, low, high) => {
|
||||||
return
|
if (low === high) {
|
||||||
}
|
P.push([...arr])
|
||||||
for (let i = low; i <= high; i++) {
|
// console.log(arr.join(' '))
|
||||||
arr = swap(arr, low, i)
|
return P
|
||||||
permutations(arr, low + 1, high)
|
}
|
||||||
|
for (let i = low; i <= high; i++) {
|
||||||
|
arr = swap(arr, low, i)
|
||||||
|
permute(arr, low + 1, high)
|
||||||
|
}
|
||||||
|
return P
|
||||||
}
|
}
|
||||||
|
return permute(arr, 0, arr.length - 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Driver Code
|
export { permutations }
|
||||||
const input = [1, 2, 3]
|
|
||||||
permutations(input, 0, input.length - 1)
|
|
||||||
|
14
Backtracking/tests/GeneratePermutations.test.js
Normal file
14
Backtracking/tests/GeneratePermutations.test.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { permutations } from '../GeneratePermutations'
|
||||||
|
|
||||||
|
describe('Permutations', () => {
|
||||||
|
it('Permutations of [1, 2, 3]', () => {
|
||||||
|
expect(permutations([1, 2, 3])).toEqual([
|
||||||
|
[ 1, 2, 3 ],
|
||||||
|
[ 1, 3, 2 ],
|
||||||
|
[ 2, 1, 3 ],
|
||||||
|
[ 2, 3, 1 ],
|
||||||
|
[ 3, 1, 2 ],
|
||||||
|
[ 3, 2, 1 ]
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user