mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Fix #748 : Revise algorithm implementation so that it actually returns the combinations. Fix test (was not running, .mjs not matching Jest pattern) and work.
This commit is contained in:
@ -25,19 +25,21 @@ class Combinations {
|
|||||||
constructor (n, k) {
|
constructor (n, k) {
|
||||||
this.n = n
|
this.n = n
|
||||||
this.k = k
|
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) {
|
findCombinations (high = this.n, total = this.k, low = 1) {
|
||||||
if (total === 0) {
|
if (total === 0) {
|
||||||
console.log(this.combinationArray)
|
this.combinations.push([...this.current])
|
||||||
return
|
return this.combinations
|
||||||
}
|
}
|
||||||
for (let i = low; i <= high; i++) {
|
for (let i = low; i <= high; i++) {
|
||||||
this.combinationArray.push(i)
|
this.current.push(i)
|
||||||
this.findCombinations(high, total - 1, i + 1)
|
this.findCombinations(high, total - 1, i + 1)
|
||||||
this.combinationArray.pop()
|
this.current.pop()
|
||||||
}
|
}
|
||||||
|
return this.combinations
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,11 +3,11 @@ import { Combinations } from '../AllCombinationsOfSizeK'
|
|||||||
describe('AllCombinationsOfSizeK', () => {
|
describe('AllCombinationsOfSizeK', () => {
|
||||||
it('should return 3x2 matrix solution for n = 3 and k = 2', () => {
|
it('should return 3x2 matrix solution for n = 3 and k = 2', () => {
|
||||||
const test1 = new Combinations(3, 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)
|
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]])
|
||||||
})
|
})
|
||||||
})
|
})
|
Reference in New Issue
Block a user