Skip to content

Commit 4f4deac

Browse files
committed
Fix TheAlgorithms#748 : Revise algorithm implementation so that it actually returns the combinations. Fix test (was not running, .mjs not matching Jest pattern) and work.
1 parent 2edbc23 commit 4f4deac

File tree

2 files changed

+10
-8
lines changed

2 files changed

+10
-8
lines changed

Backtracking/AllCombinationsOfSizeK.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,21 @@ class Combinations {
2525
constructor (n, k) {
2626
this.n = n
2727
this.k = k
28-
this.combinationArray = [] // will be used for storing current combination
28+
this.current = [] // will be used for storing current combination
29+
this.combinations = []
2930
}
3031

3132
findCombinations (high = this.n, total = this.k, low = 1) {
3233
if (total === 0) {
33-
console.log(this.combinationArray)
34-
return
34+
this.combinations.push([...this.current])
35+
return this.combinations
3536
}
3637
for (let i = low; i <= high; i++) {
37-
this.combinationArray.push(i)
38+
this.current.push(i)
3839
this.findCombinations(high, total - 1, i + 1)
39-
this.combinationArray.pop()
40+
this.current.pop()
4041
}
42+
return this.combinations
4143
}
4244
}
4345

Backtracking/tests/AllCombinationsOfSizeK.test.mjs renamed to Backtracking/tests/AllCombinationsOfSizeK.test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ import { Combinations } from '../AllCombinationsOfSizeK'
33
describe('AllCombinationsOfSizeK', () => {
44
it('should return 3x2 matrix solution for n = 3 and k = 2', () => {
55
const test1 = new Combinations(3, 2)
6-
expect(test1.findCombinations).toEqual([[1, 2], [1, 3], [2, 3]])
6+
expect(test1.findCombinations()).toEqual([[1, 2], [1, 3], [2, 3]])
77
})
88

9-
it('should return 6x2 matrix solution for n = 3 and k = 2', () => {
9+
it('should return 6x2 matrix solution for n = 4 and k = 2', () => {
1010
const test2 = new Combinations(4, 2)
11-
expect(test2.findCombinations).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]])
11+
expect(test2.findCombinations()).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]])
1212
})
1313
})

0 commit comments

Comments
 (0)