Circular Queue in Javascript - javascript

I was going through a book on Data Structures and Algorithm with JavaScript when I found this piece of codes.
I need someone to help me explain the logic behind the code here, also the logic behind the value of var i in each method.
var i = (this._front + length) & (this._size - 1); //explain this in push()
var i = (this._front + length - 1) & (this._size - 1); // explain this in pop()
var i = (((( this._front - 1 ) & ( size - 1) ) ^ size ) - size );// explain this in unshift()
Please explain the general logic for each method, I have an issue with the use of & operator in the above statements, please why the use of & instead of %
var CircularDequeue = (()=> {
class CircularDequeue {
constructor() {
// pseudo realistic 2^x value
this._size = 1024;
this._length = 0;
this._front = 0;
this._data = [];
}
push (item) {
// get the length of the array
var length = this._length;
// calculate the end
var i = (this._front + length) & (this._size - 1);
// assign value to the current end of the data
this._data[i] = item;
// increment length for quick look up
this._length = length + 1;
// return new length
return this._length;
}
pop () {
// get the length of the array
var length = this._length;
// calculate the end
var i = (this._front + length - 1) & (this._size - 1);
// copy the value to return
var ret = this._data[i];
// remove the value from data
this._data[i] = undefined;
// reduce length for look up
this._length = length - 1;
// return value
return ret;
}
shift () {
// get the current front of queue
var front = this._front;
// capture return value
var ret = this._data[front];
// reset value in the data
this._data[front] = undefined;
// calculate the new front of the queue
this._front = (front + 1) & (this._size - 1);
// reduce the size
this._length = this._length - 1;
// return the value
return ret;
}
unshift (item) {
// get the size
var size = this._size;
// calculate the new front
var i = (((( this._front - 1 ) & ( size - 1) ) ^ size ) -
size );
// add the item
this._data[i] = item;
// increment the length
this._length = this._length + 1;
// update the new front
this._front = i;
// return the acknowledgement of the addition of the new
item
return this._length;
}
}
return CircularDequeue;
})();
module.exports = CircularDequeue;
I have tried to understand this logic but the use of bitwise & in calculating the values of var i instead of modulo operator(%) keeps confusing me

In this code something & (size - 1) is equivalent to something % size because size is a power of 2, and seeing the comment in the constructor, it is supposed to be a power of 2.
I don't see a good reason why the following has been done:
(((( this._front - 1 ) & ( size - 1) ) ^ size ) - size )
The first part ( this._front - 1 ) & ( size - 1) is always going to be a non-negative number that is less than size.
^ size will set a bit that is 0 (because the intermediate value is less than size) and then - size will clear that same bit again. So that ^ size ) - size part is a non-operation. It can be left out.
It is unclear why the author of this code preferred to work with the & operator than the %, as the latter one would also work if the size would not have been a power of two, while the & operator will only work as intended when size is a power of 2.
To see how & works, take for example that the left side is 1025, which means it is out of range. In binary 1025 is 10000000001. On the other hand we have size which is 1024. size - 1 in binary is 1111111111.
So we have this & operation:
10000000001
1111111111
----------- &
0000000001
So this operation effectively removes any excess bits from the left side operand, whether they come from a negative value or from a value that is not less than size.

Related

Paper Cut into Minimum Number of Squares in JS

I'm trying to convert the algorithme from https://www.geeksforgeeks.org/paper-cut-minimum-number-squares-set-2/
in javascript.
I was able to translate the first algo in js (https://www.geeksforgeeks.org/paper-cut-minimum-number-squares/) easily, but the greedy approach isn't precise enough.
I'm having some issues with js and recursive programming, on my first attempts, I got the Maximum call stack size exceeded error, so I tried to raise it with node --stack-size=10000 <app>, but in this case the script doesn't output anything.
This is what I have right now :
// JS program to find minimum
// number of squares
// to cut a paper using Dynamic Programming
const MAX = 300
let dp = new Array(MAX);
for (let i = 0; i < dp.length; i++) {
dp[i] = new Array(MAX).fill(0);
}
// Returns min number of squares needed
function minimumSquare(m, n) {
// Initializing max values to
// vertical_min
// and horizontal_min
let vertical_min = 10000000000
let horizontal_min = 10000000000
// If the given rectangle is
// already a square
if (m === n) {
return 1
}
// If the answer for the given rectangle is
// previously calculated return that answer
if (dp[m][n] !== 0) {
return dp[m][n]
}
// The rectangle is cut horizontally and
// vertically into two parts and the cut
// with minimum value is found for every
// recursive call.
for (let i=1; i<m/2+1; i++) {
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
horizontal_min = Math.min(minimumSquare(i, n) + minimumSquare(m-i, n), horizontal_min)
}
for (let j=1; j<n/2+1; j++) {
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
vertical_min = Math.min(minimumSquare(m, j) + minimumSquare(m, n-j), vertical_min)
}
// Minimum of the vertical cut or horizontal
// cut to form a square is the answer
dp[m][n] = Math.min(vertical_min, horizontal_min)
return dp[m][n]
}
// Driver code
let m = 30
let n = 35
console.log(minimumSquare(m, n))
//This code is contributed by sahilshelangia
Expected Result would be the minimal number of squares possible in a rectangle of m, n dimensions.
For example, for 30x15 rectangle, the script would output 2.
I have added 2 new conditions to fix the issue. those are
If m is exactly divisible by n then return value m/n
If n is exactly divisible by m then return value n/m
const MAX = 300
let dp = new Array(MAX);
for (let i = 0; i < dp.length; i++) {
dp[i] = new Array(MAX).fill(0);
}
// Returns min number of squares needed
function minimumSquare(m, n) {
// Initializing max values to
// vertical_min
// and horizontal_min
let vertical_min = 10000000000
let horizontal_min = 10000000000
// If the given rectangle is
// already a square
if (m === n) {
return 1
}
// If the answer for the given rectangle is
// previously calculated return that answer
if (dp[m][n] !== 0) {
return dp[m][n]
}
if(m%n==0){//if m is exactly divisible by n
dp[m][n] = m/n
return m/n;
}
if(n%m==0){//if n is exactly divisible by m
dp[m][n] = n/m
return n/m;
}
// The rectangle is cut horizontally and
// vertically into two parts and the cut
// with minimum value is found for every
// recursive call.
for (let i=1; i<m/2+1; i++) {
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
horizontal_min = Math.min(minimumSquare(i, n) + minimumSquare(m-i, n), horizontal_min)
}
for (let j=1; j<n/2+1; j++) {
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
vertical_min = Math.min(minimumSquare(m, j) + minimumSquare(m, n-j), vertical_min)
}
// Minimum of the vertical cut or horizontal
// cut to form a square is the answer
dp[m][n] = Math.min(vertical_min, horizontal_min)
return dp[m][n]
}
// Driver code
let m = 30
let n = 35
console.log(minimumSquare(m, n))

Addition with carryover in arrays in pure Javascript

I want to create simple addition of array with carryover. Also need carryover and result value for display.
Something like this:-
e.g var input = [[0,0,9],[0,9,9]];
var carryover = [];
var result = [];
Thanks...
The two parts you might have been struggling with, I assume would be how you get the carry, and how you get the result..
result [diget] = t % 10;
The % 10 part is what is called modulus, here I'm doing a modulus by 10, so that gets you the 10's unit value.
carryover [diget] = Math.trunc(t / 10);
For the carryover, you just then divide by 10, and then we strip the decimals,. That's what Math.trunc does.
var input = [[0,0,0,9],[0,9,9]];
var carryover = [];
var result = [];
var digetlength = Math.max(input[0].length, input[1].length);
//lets padd inputs to be same size
input[0].unshift(
...new Array(digetlength - input[0].length).fill(0));
input[1].unshift(
...new Array(digetlength - input[1].length).fill(0));
for (var diget = digetlength - 1; diget >= 0; diget -= 1) {
var t = input[0][diget] + input[1][diget];
if (diget < digetlength - 1)
t += carryover[diget + 1];
result [diget] = t % 10;
carryover [diget] = Math.trunc(t / 10);
}
result.unshift(carryover[0]);
console.log('result: ' + result.join(', '));
console.log('carry: ' + carryover.join(', '));
1.turn both numbers into array of digits, reverse them.
2.determine the end index of the for-loop with max length of above 2 arrays.
3.create the 3rd carryover digits array of zeros (don't forget the extra digit).
4.Add the respective digits from step1 and step3,
as you iterate through each of digits from right to left,
4.1 if the sum is greater than 9 then add 1 into next carryover slot.
5. you should have array of carried over digits when the for-loop is done
count the number of 1s you have in them.
function numberOfCarryOperations(num1, num2) {
const dd1 = [...num1.toString()].reverse()
const dd2 = [...num2.toString()].reverse()
const end = Math.max(dd1.length, dd2.length)
const carry = Array(end+1).fill(0)
for (let i = 0; i < end; i++) {
//console.log(i,(Number(dd1[i]?dd1[i]:0)),Number(dd2[i]?dd2[i]:0),carry)
if (((Number(dd1[i]?dd1[i]:0)) + Number(dd2[i]?dd2[i]:0) + carry[i]) > 9) {
carry[i+1] = 1
}
//console.log('-----',carry)
}
//console.log(num1, num2,carry)
return carry.reduce((sum,curr)=>sum+curr)
}
Here is my attempt. It will accept the following as input:
Any number of input arrays
The input arrays don't all need to have the same number of items
I've added code comments to explain what goes on, I hope they're informative enough to explain the answer.
const
input = [
[0,0,9],
[0,9,9],
[1,0,9,9]
];
function getMaxArrayLength(values) {
// Determine the number of items in the longest array. Initialize the reduce with 0.
return values.reduce((maxLength, array) => {
// Return the largets number between the last largest number and the
// length of the current array.
return Math.max(maxLength, array.length);
}, 0);
}
function sumValues(values) {
const
// Determine the number of items in the longest array.
maxLength = getMaxArrayLength(values),
result = [],
carry = [];
// Loop over the length of the longest array. The value of index will be substracted from
// the length of the input arrays. Therefore it is easier to start at 1 as this will
// return a proper array index without needing to correct it.
for (let index = 1; index <= maxLength; index++) {
const
// Get the carryover value from the last sum or 0 in case there is no previous value.
carryValue = (carry.length === 0) ? 0 : carry[carry.length-1],
// Sum up all the values at the current index of all the input arrays. After summing up
// all the values, also add the carry over from the last sum.
sum = values.reduce((sum, array) => {
// Determine the index for the current array. Start at the end and substract the
// current index. This way the values in the array are processed last to first.
const
arrayIndex = array.length - index;
// It could be the current array doesn't have as many items as the longest array,
// when the arrayIndex is less than 0 just return the current result.
if (arrayIndex < 0) {
return sum;
}
// Return the accumulated value plus the value at the current index of the
// current source array.
return sum + array[arrayIndex];
}, 0) + carryValue;
// The carry over value is the number of times 10 fits into the sum. This should be rounded
// down so for instance 5/10=.5 becomes 0.
carry.push(Math.floor(sum / 10));
// Push the remainder of the sum divided by 10 into the result so 15 % 10 = 5.
result.push(sum % 10);
}
// Return the carry over and the result, reverse the arrays before returning them.
return {
carryOver: carry.reverse(),
result: result.reverse()
};
}
const
result = sumValues(input);
console.log(`Carry over: ${result.carryOver}`);
console.log(`Result: ${result.result}`);

How to return an array of values, the sums of which equal a specified number

I'm trying to create an array of numbers of a set length, defining the minimum and a maximum number in the set, and letting a function determine the rest of the numbers between. The kicker is that the sum of this array of numbers must be equal to a predetermined value. The trick is figuring out how that function works.
I found this on stack overflow, which got me the following function:
export const distributeValues = (amount, weights=[]) => {
const distributedAmounts = []
let totalWeights = weights.reduce( (a,b) => a + b)
weights.forEach( weight => {
const weightValue = parseFloat(weight)
const percentage = weightValue / totalWeights
const distributedAmount = Math.round(percentage * amount)
distributedAmounts.push(distributedAmount)
totalWeights -= weightValue
amount -= distributedAmount
})
return distributedAmounts
}
This seems like a good start, but I actually need to work backwards; I'm trying to figure out a function that will give me the weights that would be passed into the above function.
Right now, I have this, a function broken into two parts (apologies for the redundancy):
export const getDistributions = (amount, distributions, modifier) => {
const values = []
let amountLeft = amount;
for (let i = 0; i < distributions; i++ ) {
const value = Math.max(Math.round((amountLeft / (modifier || 4))),1)
amountLeft -= value
values.push(value)
}
// -------------------------------------------- //
// --- correct for cases where total values --- //
// --- end up greater/less than amount --- //
// -------------------------------------------- //
let iterator = 0
let totalAssignedValue = values.reduce((a,b) => a+b);
const lastIndex = (values.length - 1);
const getIndex = (iterator, values) => {
return iterator > lastIndex ? iterator % lastIndex : iterator
}
while (totalAssignedValue > amount) {
iterator = getIndex(iterator)
if (iterator !== lastIndex && iterator !== 0 && values[iterator] > 1) {
values[iterator]--
}
iterator ++
totalAssignedValue = values.reduce((a,b) => a+b);
}
while (totalAssignedValue < amount) {
iterator = getIndex(iterator)
if (iterator !== lastIndex && iterator !== 0) {
values[iterator]++
}
iterator ++
totalAssignedValue = values.reduce((a,b) => a+b);
}
// -------------------------------------------- //
// -------------- end correction -------------- //
// -------------------------------------------- //
return values;
}
The first part tries and distributes the values, but invariably I end up with values that are greater or lesser than the input amount, so there's a second part of the equation that fixes that. Seems a little unclean though, and it's a little arbitrary how the remainders get distributed, so a pure mathematical solution would be great.
I'm starting to wonder if I'm going to need calculus for this, because I basically have the integral (the sum of the array's values), the range of the integral (min and max values), and now have to figure out the formula for the curve. This may be overkill at this point, though.
Thanks for the input!
How about this? First create the set in such way that the first member is the minimum, the second member is minimum + 1, the third minimum + 2, etc. Then sum up the numbers in the set and subtract the sum from the predetermined value. Then distribute the result of the subtraction among all the numbers in the set as outlined betlow.
Set makeSet(int preDet, int min, int max, int setLength)
{
if((max + max - setLength + 1) * setLength / 2 < preDet) return null;
if((min + min + setLength - 1) * setLength / 2 > preDet) return null;
Set set = Set(setLength);
int val = min;
for (int i = 0; i < setLength; i++)
{
set[i] = val++;
}
int sum = (min + val - 1) * setLength / 2;
int dev = preDet - sum;
if(dev)
{
int adj = dev / setLength;
if(dev % setLength) adj++;
for(int i = setLength -1; dev; i--)
{
if(adj > dev) adj = dev;
set[i] += adj;
dev -= adj;
}
}
return set;
}

Algorithm that involves rounding and multiples

So I have a problem where I have an array of some length (usually long). I have an initial start index into that array and a skip value. So, if I have this:
var initial = 5;
var skip = 10;
Then I'd iterate over my array with indexes 5, 15, 25, 35, etc.
But then I may get a new start value and I need to find the closest value to the initial plus or minus a multiple of the skip and then start my skip. So if my new value is 23 then I'd iterate 25, 35, 45, etc.
The algorithm I have for this is:
index = (round((start - initial) / skip) * skip) + initial
And then I need a check to see if index has dropped below zero:
while(index < 0) index += skip;
So my first question is if there's a name for this? A multiple with random start?
My second question is if there's a better way? I don't think what I have is terribly complicated but if I'm missing something I'd like to know about it.
If it matters I'm using javascript.
Thanks!
Edit
Instead of
while(index < 0) index += skip;
if we assume that both initial and skip are positive you can use:
if (index < 0) index = initial % skip;
To get the closest multiple of a number to a test number: See if the modulo of your test number is greater than number/2 and if so, return number - modulo:
function closestMultiple(multipleTest,number)
{
var modulo = multipleTest%number;
if(0 == modulo )
{
return multipleTest;
}
else
{
var halfNumber = number/2;
if(modulo >= halfNumber)
{
return multipleTest + (number-modulo);
}
else
{
return multipleTest - modulo;
}
}
}
To check if a number is a multiple of another then compare their modulo to 0:
function isMultiple(multipleTest,number)
{
return 0 == multipleTest%number;
}
You might want to add some validations for 0 in case you expect any inside closestMultiple.
The value of index computed as you put it
index = round((start - initial)/skip) * skip + initial
is indeed the one that minimizes the distance between the sequence with general term
aj = j * skip + initial
and start.
Therefore, index can only be negative if start lies to the left of
(a-1 + a0)/2 = initial - skip/2
in other words, if
start < initial - skip/2.
So, only in that case you have to redefine index to 0. In pseudo code:
IF (start < (initial - skip/2))
index = 0
ELSE
index = round((start - initial)/skip) * skip + initial
Alternatively, you could do
index = round((start - initial)/skip) * skip + initial
IF index < 0 THEN index = 0
which is the same.
No while loop required:
function newNum(newstart, initial, skip) {
var xLow = newstart + Math.abs(newstart - initial) % skip;
var xHi = newstart + skip;
var result = (xLow + xHi) / 2 > newstart ? xLow : xHi;
if (result < 0) result += skip;
return result;
}
Take the distance between your new starting point and your initial value, and find out what the remainder would be if you marched towards that initial value (Modulus gives us that). Then you just need to find out if the closest spot is before or after the starting point (I did this be comparing the midpoint of the low and high values to the starting point).
Test:
newNum(1, 20, 7) = 6
newNum(-1, 20, 7) = 6
newNum(180, 10, 3) = 182
(Even though you stated in your comments that the range of the new starting point is within the array bounds, notice that it doesn't really matter).

How to convert last 4 bytes in an array to an integer?

If I have an Uint8Array array in JavaScript, how would I get the last four bytes and then convert that to an int? Using C# I would do something like this:
int count = BitConverter.ToInt32(array, array.Length - 4);
Is there an inequivalent way to do this using JavaScript?
Access the underlying ArrayBuffer and create a new TypedArray with a slice of its bytes:
var u8 = new Uint8Array([1,2,3,4,5,6]); // original array
var u32bytes = u8.buffer.slice(-4); // last four bytes as a new `ArrayBuffer`
var uint = new Uint32Array(u32bytes)[0];
If the TypedArray does not cover the entire buffer, you need to be a little trickier, but not much:
var startbyte = u8.byteOffset + u8.byteLength - Uint32Array.BYTES_PER_ELEMENT;
var u32bytes = u8.buffer.slice(startbyte, startbyte + Uint32Array.BYTES_PER_ELEMENT);
This works in both cases.
If the bytes you want fit in the alignment boundary of your underlying buffer for the datatype (e.g., you want the 32-bit value of bytes 4-8 of the underlying buffer), you can avoid copying the bytes with slice() and just supply a byteoffset to the view constructor, as in #Bergi's answer.
Below is a very-lightly-tested function that should get the scalar value of any offset you want. It will avoid copying if possible.
function InvalidArgument(msg) {
this.message = msg | null;
}
function scalarValue(buf_or_view, byteOffset, type) {
var buffer, bufslice, view, sliceLength = type.BYTES_PER_ELEMENT;
if (buf_or_view instanceof ArrayBuffer) {
buffer = buf_or_view;
if (byteOffset < 0) {
byteOffset = buffer.byteLength - byteOffset;
}
} else if (buf_or_view.buffer instanceof ArrayBuffer) {
view = buf_or_view;
buffer = view.buffer;
if (byteOffset < 0) {
byteOffset = view.byteOffset + view.byteLength + byteOffset;
} else {
byteOffset = view.byteOffset + byteOffset;
}
return scalarValue(buffer, view.byteOffset + byteOffset, type);
} else {
throw new InvalidArgument('buf_or_view must be ArrayBuffer or have a .buffer property');
}
// assert buffer instanceof ArrayBuffer
// assert byteOffset > 0
// assert byteOffset relative to entire buffer
try {
// try in-place first
// only works if byteOffset % slicelength === 0
return (new type(buffer, byteOffset, 1))[0]
} catch (e) {
// if this doesn't work, we need to copy the bytes (slice them out)
bufslice = buffer.slice(byteOffset, byteOffset + sliceLength);
return (new type(bufslice, 0, 1))[0]
}
}
You would use it like this:
// positive or negative byte offset
// relative to beginning or end *of a view*
100992003 === scalarValueAs(u8, -4, Uint32Array)
// positive or negative byte offset
// relative to the beginning or end *of a buffer*
100992003 === scalarValue(u8.buffer, -4, Uint32Array)
Do you have an example? I think this would do it:
var result = ((array[array.length - 1]) |
(array[array.length - 2] << 8) |
(array[array.length - 3] << 16) |
(array[array.length - 4] << 24));
Nowadays if you can live with IE 11+ / Chrome 49+ / Firefox 50+, then you can use DataView to make your life almost as easy as in C#:
var u8array = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]); // -1
var view = new DataView(u8array.buffer)
console.log("result:" + view.getInt32());
Test it here: https://jsfiddle.net/3udtek18/1/
A little inelegant, but if you can do it manually based on the endianess.
Little endian:
var count = 0;
// assuming the array has at least four elements
for(var i = array.length - 1; i >= array.length - 4; i--)
{
count = count << 8 + array[i];
}
Big endian:
var count = 0;
// assuming the array has at least four elements
for(var i = array.length - 4; i <= array.length - 1 ; i++)
{
count = count << 8 + array[i];
}
This can be extended to other data lengths
Edit: Thanks to David for pointing out my typos
I'm surprised that the other answers don't use the native Buffer object, which provides a lot of this tooling in a simple, native library. It's possible that this library isn't widely used for bitpacking/unpacking simply because people don't think to check here and it took me a while to find it, too, but it's the right tool for bitpacking/unpacking in nodejs/javascript/typescript.
You can use it like so:
// Create a simple array with 5 elements. We'll pop the last 4 and you should expect the end value to be 1 because this is a little-endian array with all zeros other than the 1 in the littlest(?)-endian
const array = [0, 1, 0, 0, 0]
// get the last 4 elements of your array and convert it to a Buffer
const buffer = Buffer.from(array.slice(-4));
// Use the native Buffer type to read the object as an (U) unsigned (LE) little-endian 32 (32 bits) integer
const value = Buffer.readUInt32LE();
Or, more concisely:
const value = Buffer.from(array.slice(-4)).readUInt32LE();
It should be more efficient to just create an Uint32Array view on the same ArrayBuffer and accessing the 32-bit number directly:
var uint8array = new Uint8Array([1,2,3,4,5,6,7,8]);
var uint32array = new Uint32Array(
uint8array.buffer,
uint8array.byteOffset + uint8array.byteLength - 4,
1 // 4Bytes long
);
return uint32array[0];
var a = Uint8Array(6)
a.set([1,2,8,0,0,1])
i1 = a[a.length-4];
i2 = a[a.length-3];
i3 = a[a.length-2];
i4 = a[a.length-1];
console.log(i1<<24 | i2<<16 | i3<<8 | i4);
It's a shame there are not build in ways to do this.
I needed to read variables of variable sizes so based on Imortenson answer I've wrote this little function where p is read position and s is number of bytes to read:
function readUInt(arr, p, s) {
var r = 0;
for (var i = s-1; i >= 0; i--) {
r |= arr[p + i] << (i * 8);
} return r >>> 0;
}
var iable = readUint(arr, arr.length - 4, 4);

Categories