|
| 1 | +/** |
| 2 | + * @param {number} size |
| 3 | + */ |
| 4 | +var Bitset = function(size) { |
| 5 | + this.s = Array.from({ length:2 }, () => Array()) |
| 6 | + this.cnt = 0 |
| 7 | + this.now = 0 |
| 8 | + for (let i = 0; i < size; i++) { |
| 9 | + this.s[this.now].push( '0'); |
| 10 | + this.s[this.now ^ 1].push( '1'); |
| 11 | + } |
| 12 | +}; |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number} idx |
| 16 | + * @return {void} |
| 17 | + */ |
| 18 | +Bitset.prototype.fix = function(idx) { |
| 19 | + if (this.s[this.now][idx] == '1') return; |
| 20 | + // swap(this.s[this.now][idx], this.s[this.now ^ 1][idx]); |
| 21 | + const tmp = this.s[this.now][idx] |
| 22 | + this.s[this.now][idx] = this.s[this.now ^ 1][idx] |
| 23 | + this.s[this.now ^ 1][idx] = tmp |
| 24 | + this.cnt++; |
| 25 | +}; |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number} idx |
| 29 | + * @return {void} |
| 30 | + */ |
| 31 | +Bitset.prototype.unfix = function(idx) { |
| 32 | + if (this.s[this.now][idx] == '0') return; |
| 33 | + // swap(this.s[this.now][idx], this.s[this.now ^ 1][idx]); |
| 34 | + const tmp = this.s[this.now][idx] |
| 35 | + this.s[this.now][idx] = this.s[this.now ^ 1][idx] |
| 36 | + this.s[this.now ^ 1][idx] = tmp |
| 37 | + this.cnt--; |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * @return {void} |
| 42 | + */ |
| 43 | +Bitset.prototype.flip = function() { |
| 44 | + this.now = this.now ^ 1; |
| 45 | + this.cnt = this.s[0].length - this.cnt; |
| 46 | +}; |
| 47 | + |
| 48 | +/** |
| 49 | + * @return {boolean} |
| 50 | + */ |
| 51 | +Bitset.prototype.all = function() { |
| 52 | + return this.cnt == this.s[0].length; |
| 53 | +}; |
| 54 | + |
| 55 | +/** |
| 56 | + * @return {boolean} |
| 57 | + */ |
| 58 | +Bitset.prototype.one = function() { |
| 59 | + return this.cnt !== 0 |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * @return {number} |
| 64 | + */ |
| 65 | +Bitset.prototype.count = function() { |
| 66 | + return this.cnt; |
| 67 | +}; |
| 68 | + |
| 69 | +/** |
| 70 | + * @return {string} |
| 71 | + */ |
| 72 | +Bitset.prototype.toString = function() { |
| 73 | + return this.s[this.now].join(''); |
| 74 | +}; |
| 75 | + |
| 76 | + |
| 77 | +/** |
| 78 | + * Your Bitset object will be instantiated and called as such: |
| 79 | + * var obj = new Bitset(size) |
| 80 | + * obj.fix(idx) |
| 81 | + * obj.unfix(idx) |
| 82 | + * obj.flip() |
| 83 | + * var param_4 = obj.all() |
| 84 | + * var param_5 = obj.one() |
| 85 | + * var param_6 = obj.count() |
| 86 | + * var param_7 = obj.toString() |
| 87 | + */ |
| 88 | + |
0 commit comments