File tree Expand file tree Collapse file tree 1 file changed +24
-22
lines changed Expand file tree Collapse file tree 1 file changed +24
-22
lines changed Original file line number Diff line number Diff line change 21
21
- Once we get all combinations of that element, pop it and do same for next element
22
22
*/
23
23
24
- class Combinations {
25
- constructor ( n , k ) {
26
- this . n = n
27
- this . k = k
28
- this . current = [ ] // will be used for storing current combination
29
- this . combinations = [ ]
30
- this . i = 1
24
+ function generateCombinations ( n , k ) {
25
+ let currentCombination = [ ]
26
+ let allCombinations = [ ] // will be used for storing all combinations
27
+ let currentValue = 1
28
+
29
+ function findCombinations ( ) {
30
+ if ( currentCombination . length === k ) {
31
+ // Add the array of size k to the allCombinations array
32
+ allCombinations . push ( [ ...currentCombination ] )
33
+ return
34
+ }
35
+ if ( currentValue > n ) {
36
+ // Check for exceeding the range
37
+ return
38
+ }
39
+ currentCombination . push ( currentValue ++ )
40
+ findCombinations ( )
41
+ currentCombination . pop ( )
42
+ findCombinations ( )
43
+ currentValue --
31
44
}
32
45
33
- findCombinations ( ) {
34
- if ( this . current . length == this . k ) { //will add the array of size k to combinations array
35
- this . combinations . push ( [ ...this . current ] )
36
- return
37
- }
38
- if ( this . i > this . n ) //check for exceeding range
39
- return
40
- this . current . push ( this . i ++ )
41
- this . findCombinations ( )
42
- this . current . pop ( )
43
- this . findCombinations ( )
44
- this . i --
45
- return this . combinations
46
- }
46
+ findCombinations ( )
47
+
48
+ return allCombinations
47
49
}
48
50
49
- export { Combinations }
51
+ export { generateCombinations }
You can’t perform that action at this time.
0 commit comments