Skip to content

Commit bc8c196

Browse files
authored
Create 1286-iterator-for-combination.js
1 parent 0519238 commit bc8c196

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

1286-iterator-for-combination.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @param {string} characters
3+
* @param {number} combinationLength
4+
*/
5+
const CombinationIterator = function (characters, combinationLength) {
6+
this.arr = build(combinationLength, characters.split('').sort().join(''))
7+
this.pos = 0
8+
}
9+
10+
/**
11+
* @return {string}
12+
*/
13+
CombinationIterator.prototype.next = function () {
14+
if (this.pos < this.arr.length) {
15+
return this.arr[this.pos++]
16+
}
17+
}
18+
19+
/**
20+
* @return {boolean}
21+
*/
22+
CombinationIterator.prototype.hasNext = function () {
23+
return this.pos < this.arr.length
24+
}
25+
26+
/**
27+
* Your CombinationIterator object will be instantiated and called as such:
28+
* var obj = new CombinationIterator(characters, combinationLength)
29+
* var param_1 = obj.next()
30+
* var param_2 = obj.hasNext()
31+
*/
32+
function build(max, str, out = [], curr = '') {
33+
if (curr.length === max) {
34+
out.push(curr)
35+
return
36+
} else {
37+
for (let i = 0; i < str.length; i++) {
38+
build(max, str.slice(i + 1), out, curr + str[i])
39+
}
40+
}
41+
42+
return out
43+
}

0 commit comments

Comments
 (0)