Skip to content

Instantly share code, notes, and snippets.

@vadim2404
Last active November 24, 2015 13:19
Show Gist options
  • Save vadim2404/d1fb4d0b36b14e5ae211 to your computer and use it in GitHub Desktop.
Save vadim2404/d1fb4d0b36b14e5ae211 to your computer and use it in GitHub Desktop.
module.exports = (function () {
var prev = function (x) {
return x & (x - 1);
}, next = function (x) {
return (x | (x - 1)) + 1;
}, Summator = function (length) {
if (1 > length) {
throw {
message: 'Length is too small',
};
}
this.length = length;
this.container = [];
for (var i = 0; i <= length; ++i) {
this.container.push(0);
}
};
Summator.prototype = {
modify: function (position, value) {
if (1 > position || this.length < position) {
throw {
message: 'Invalid position "' + position + '" [1, length]'
};
}
for (var x = position; x <= this.length; x = next(x)) {
this.container[x] += value;
}
},
findSum: function (left, right) {
if (1 > left || 1 > right || this.length < left || this.length < right || right < left) {
throw {
message: 'Invalid left or right argument "' + left + '", "' + right + '"'
};
}
var result = 0;
for (var x = right; x; x = prev(x)) {
result += this.container[x];
}
for (var x = left - 1; x; x = prev(x)) {
result -= this.container[x];
}
return result;
}
};
return Summator;
})();
@vadim2404
Copy link
Author

var Summator = require('./summator.js'),
    s = new Summator(10);
s.modify(1, 1);
s.modify(2, 1);
s.findSum(1, 2); // 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment