GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — added Backtracking/AllCombinationsOfSizeK · Algorithms-Learn/JavaScript@6919e85

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • Backtracking
    • AllCombinationsOfSizeK.js
  • package-lock.json
  • package.json
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎Backtracking/AllCombinationsOfSizeK.js‎

Copy file name to clipboard
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Problem: Given two numbers, n and k, make all unique combinations of k numbers from 1 to n and in sorted order
3+
4+
What is combinations?
5+
- Combinations is selecting items froms a collections without considering order of selection
6+
7+
Example:
8+
- We have an apple, a banana, and a jackfruit
9+
- We have three objects, and need to choose two items, then combinations will be
10+
11+
1. Apple & Banana
12+
2. Apple & Jackfruit
13+
3. Banana & Jackfruit
14+
15+
To read more about combinations, you can visit the following link:
16+
- https://betterexplained.com/articles/easy-permutations-and-combinations/
17+
18+
Solution:
19+
- We will be using backtracking to solve this questions
20+
- Take one element, and make all them combinations for k-1 elements
21+
- Once we get all combinations of that element, pop it and do same for next element
22+
*/
23+
24+
class Combinations {
25+
constructor (n, k) {
26+
this.n = n
27+
this.k = k
28+
this.combinationArray = [] // will be used for storing current combination
29+
}
30+
31+
findCombinations (high = this.n, total = this.k, low = 1) {
32+
if (total === 0) {
33+
console.log(this.combinationArray)
34+
return
35+
}
36+
for (let i = low; i <= high; i++) {
37+
this.combinationArray.push(i)
38+
this.findCombinations(high, total - 1, i + 1)
39+
this.combinationArray.pop()
40+
}
41+
};
42+
}
43+
44+
/*
45+
Driver Code
46+
47+
Test Case 1: n = 3, k = 2
48+
Test Case 2: n = 4, k = 2
49+
*/
50+
51+
console.log('\nFirst Test Case')
52+
const test1 = new Combinations(3, 2)
53+
test1.findCombinations()
54+
55+
console.log('\nSecond Test Case')
56+
const test2 = new Combinations(4, 2)
57+
test2.findCombinations()

0 commit comments

Comments
0 (0)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.