Skip to content

Commit 2074d6b

Browse files
authored
Update 1286-iterator-for-combination.js
1 parent 88b94e6 commit 2074d6b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

1286-iterator-for-combination.js

+54
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,57 @@ CombinationIterator.prototype.hasNext = function() {
9292
* var param_2 = obj.hasNext()
9393
*/
9494

95+
// another
96+
97+
/**
98+
* @param {string} characters
99+
* @param {number} combinationLength
100+
*/
101+
const CombinationIterator = function(characters, combinationLength) {
102+
const res = [], len = combinationLength, str = characters, n = str.length
103+
helper()
104+
105+
// console.log(res)
106+
this.arr = res
107+
this.idx = 0
108+
109+
function helper() {
110+
const limit = 1 << n
111+
for(let i = limit - 1; i > 0; i--) {
112+
let tmp = i, ts = '', idx = n - 1
113+
while(tmp) {
114+
if(tmp & 1) {
115+
ts = str[idx] + ts
116+
}
117+
idx--
118+
tmp = (tmp >> 1)
119+
}
120+
if(ts.length === len) res.push(ts)
121+
}
122+
}
123+
};
124+
125+
/**
126+
* @return {string}
127+
*/
128+
CombinationIterator.prototype.next = function() {
129+
if(this.hasNext()) {
130+
return this.arr[this.idx++]
131+
}
132+
};
133+
134+
/**
135+
* @return {boolean}
136+
*/
137+
CombinationIterator.prototype.hasNext = function() {
138+
return this.arr[this.idx] != null
139+
};
140+
141+
/**
142+
* Your CombinationIterator object will be instantiated and called as such:
143+
* var obj = new CombinationIterator(characters, combinationLength)
144+
* var param_1 = obj.next()
145+
* var param_2 = obj.hasNext()
146+
*/
147+
148+

0 commit comments

Comments
 (0)