Saturday, October 13, 2012

Efficiently implement N stacks in a single array.


General algorithm to solve this problem is as follows,
 1. For given stack count determine start/top count for every stack.
 3. Determine maximum value every stack can reach.
 4. While pushing element on a particular stack use it'sown top and max value to determine the push location as well as check is stack is full.
 5. While poping out element from particular stck use max/top values for that stack and update the same as well as check if stack is empty.
---------------------------------------------------------------------------------


/**
 * This class implements N stacks in given size of array.
 */
public class NStack
{
/** Array in which we will implement Stack.*/
int[] _array;
/** Size of the array.*/
int _size;
/** Array to hold top for all N stacks.*/
int[] _topCount;
/** Array to hold max value for all N stacks.*/
int[] _maxSize;
/** Value of N for number of stacks to implement.*/
int _stackCount;

/**
* Constructor.
* @param size Size of an array.
* @param stackSize Number of stacks to implement.
*/
public NStack(int size, int stackSize)
{
// Initialize.
_size = size;
_stackCount = stackSize;
_topCount = new int[_stackCount];
_maxSize = new int[_stackCount];
// Get initializes top count as well as max count for all N stacks.
for (int i = 0 ; i < _stackCount ; i++)
{
_topCount[i] = i - _stackCount;
_maxSize[i] = _size/_stackCount * _stackCount + i ;
if (i >= _size % _stackCount)
{
_maxSize[i] -= _stackCount;
}
}
_array = new int[_size];
}

/**
* Push element on given stack.
* @param item Item to push on stack.
* @param stackNum Stack number 1<->N.
*/
public void push(int item, int stackNum)
{
if (_topCount[stackNum - 1] + _stackCount <= _maxSize[stackNum - 1])
{
_topCount[stackNum - 1] += _stackCount;
_array[_topCount[stackNum - 1]] = item;
System.out.println("Pushing Element " + item + " @ position " + _topCount[stackNum - 1]);
}
else
{
System.out.println("Stack " + stackNum + " is Full :(.");
}
}

/**
* Pop item from given stack.
* @param stackNum Stack from which item is poped.
* @return Item poped -1 if stack is empty.
*/
public int pop(int stackNum)
{
int val = -1;
if (_topCount[stackNum -1] < 0)
{
System.out.println("Stack " + stackNum + " is Empty :(.");
}
else
{
val = _array[_topCount[stackNum -1]];
_topCount[stackNum -1] -= _stackCount;
}
return val;
}
}

No comments: