Last active
November 24, 2015 13:19
-
-
Save vadim2404/d1fb4d0b36b14e5ae211 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
})(); |
Author
vadim2404
commented
Oct 14, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment