Thursday, October 05, 2006

Inserting into arrays – part 2

Today, let us write a program to insert our stuff into an empty locker. As a first step, let us just find an empty locker and put our stuff in.
Assumptions:
(1) There are only 10 lockers in the locker room, numbering 0 to 9.
(2) A locker is empty if its content contains the string “empty” in it.

Question: Why are the lockers numbered 0 – 9 instead of 1 to 10? We shall see that a little later. For now, let us just assume that they are numbered 0 – 9.

In order to put our stuff into an empty locker, we need to first find one. Assuming all the lockers are closed, irrespective of whether they are empty or not, we would have to open and inspect each locker to check whether it is empty or not. Let us do the same with our function, as below:

public int findEmptyLocker()
{
   for (int lockerPosition=0; lockerPosition < 10; lockerPosition++)
   {
       if (arr[lockerPosition].content.equalsIgnoreCase("empty"))
          return lockerPosition;
    }
    return -1;
}

Let us examine the above function closely. The for loop can be read as follows:
(1) Start from locker at position 0.
(2) Repeat the code below as long as locker position is less than 10.
(3) At the end of each loop, increment the locker position by 1.

So, first the function starts from locker 0. It checks whether its contents is equal to “empty”. If it is, the function returns the position of the empty locker [ We do not need to check further as we have found a empty locker and so the loop does not proceed further]. If not, the loop continues with locker number 1 and so on until locker number 9 [or we find an empty locker]. If no empty locker is found, it returns -1 indicating that there are no empty lockers.

Let us see how this function can be used:

public static void main(String[] args)
{
    //… some code here
    ////////////////////////////////////////////////////////////////////
    int emptyLockerPos = lockerRoom.findEmptyLocker();
    if (emptyLockerPos != -1) // that is if there is an empty locker.
       lockerRoom.arr[emptyLockerPos].content = myStuff;//put my stuff into it.
    /////////////////////////////////////////////////////////////////////
    // … some more code here
}

That’s it. Now we have found an empty locker and put our stuff into it.