Computer Science I (CS 170)
Dr. William J. Joel, WS 110, 7-9353
Parking lot problem (source code)

// cLot.cpp
// 5/4/01, William Joel

#include <iostream.h>

class cLot {
private:
   int spaces[5][3],
       cars[15][2],
       rowCnt[5];
   bool inLot[15];
public:
   cLot();
   void removeCar(int car);
   void moveCar(int row, int space);
   void displayLot();
   void run();
};

cLot::cLot()
{
   int r;
   for(r=0;r<5;r++)
   {
    // Set car in first space
    spaces[r][0] = r+1;
    cars[r][0] = r;
    cars[r][1] = 0;
    inLot[r] = true;
    // Set car in second space
    spaces[r][1] = r+6;
    cars[r+5][0] = r;
    cars[r+5][1] = 1;
    rowCnt[r] = 2;
    inLot[5+r] = true;
    // Set car in third space
    spaces[r][2] = 0;
    inLot[10+r] = false;
 }
}

void cLot::removeCar(int car)
{
 int row, space;
 car = car - 1;
 row = cars[car][0]; // Get row for car to be moved
 space = cars[car][1]; // Get space for car to be moved
 while (rowCnt[row] > (space+1)) // Move blocking cars
  moveCar(row,rowCnt[row]-1);
 spaces[row][space] = 0; // Remove car
 rowCnt[row]--;
 inLot[car] = false;
 cout << "Remove car: " << car+1 << endl;
 displayLot();
}

void cLot::moveCar(int row, int space)
{
 int car;
 int moveRow;
 car = spaces[row][space]; // Get car to be moved
 moveRow = 0;
 while ((rowCnt[moveRow] == 3) || (row == moveRow)) // Find empty space to move to
  moveRow++;
 spaces[moveRow][rowCnt[moveRow]] = car; // Move car to new
 cars[car-1][0] = moveRow;
 cars[car-1][1] = rowCnt[moveRow];
 rowCnt[moveRow]++;
 spaces[row][space] = 0; // Empty old space
 rowCnt[row]--;
 cout << "Move car: " << car << endl;
 displayLot();
}

void cLot::displayLot()
{
   int row,spc;
   // For each space ...
   for (spc=0;spc<3;spc++)
   {
    // For each row ...
  for(row=0;row<5;row++)
  {
   cout.width(2);
   cout << " | " << spaces[row][spc];
  }
  cout << " |" << endl;
   }
   cout << endl;
   cout << "Cars in lot";
   for(int car=0;car<15;car++)
    if(inLot[car])
     cout << "-" << car+1;
 cout << endl;
 cout << endl;
}

void cLot::run()
{
   int car;
   displayLot();
   do {
      cout << "Enter number of car to remove (1-15) or -1 to exit: ";
      cin >> car;
      if ((car > 0) && (car < 16))
   {
         if(!inLot[car-1])
            cout << "There is no car with number " << car << endl;
         else
            removeCar(car);
   }
   } while(car != -1); // Exit on -1
}

void main()
{
   cLot myLot;
   myLot.run();
}