Skip to content

Commit

Permalink
Fix TheAlgorithms#748 : Revise algorithm implementation so that it ac…
Browse files Browse the repository at this point in the history
…tually returns the combinations. Fix test (was not running, .mjs not matching Jest pattern) and work.
  • Loading branch information
lvlte committed Oct 9, 2021
1 parent 2edbc23 commit 4f4deac
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
12 changes: 7 additions & 5 deletions Backtracking/AllCombinationsOfSizeK.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,21 @@ class Combinations {
constructor (n, k) {
this.n = n
this.k = k
this.combinationArray = [] // will be used for storing current combination
this.current = [] // will be used for storing current combination
this.combinations = []
}

findCombinations (high = this.n, total = this.k, low = 1) {
if (total === 0) {
console.log(this.combinationArray)
return
this.combinations.push([...this.current])
return this.combinations
}
for (let i = low; i <= high; i++) {
this.combinationArray.push(i)
this.current.push(i)
this.findCombinations(high, total - 1, i + 1)
this.combinationArray.pop()
this.current.pop()
}
return this.combinations
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { Combinations } from '../AllCombinationsOfSizeK'
describe('AllCombinationsOfSizeK', () => {
it('should return 3x2 matrix solution for n = 3 and k = 2', () => {
const test1 = new Combinations(3, 2)
expect(test1.findCombinations).toEqual([[1, 2], [1, 3], [2, 3]])
expect(test1.findCombinations()).toEqual([[1, 2], [1, 3], [2, 3]])
})

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

0 comments on commit 4f4deac

Please sign in to comment.