TweetFollow Us on Twitter

Oct 01 Challenge

Volume Number: 17 (2001)
Issue Number: 10
Column Tag: Programmer's Challenge

by Bob Boonstra, Westford, MA

Programmer's Assistant

How often has this happened to you? You're working on a piece of code, perhaps even a piece of Challenge code, you add a couple of lines, you compile, and you get some bizarre error. Something nothing near where you were editing. Perhaps an "Illegal function definition ..." in a routine you weren't even working on. And then you realize, eventually if you are slow, or immediately if you are less slow, that you added an "if (condition) {" statement and omitted the closing brace. Or some other simple syntax error.

Well, I happen to think that computers ought to be able to help us with this. My editor ought to do more to help me avoid mistakes. Yes, I know that some editors will balance parentheses for you, assuming you remembered to type the closing paren. But I want more. And this month's Challenge asks you to write such an editor for C/C++.

The first required feature is auto-completion of key words and user-defined names. For example, if I have defined variables "loop_index" and "loop_counter", then, after I type enough characters to uniquely identify a variable name (e.g., "loop_i"), my programmer's assistant should supply the remaining letters "ndex". The automatically supplied characters should be selected so that they are replaced in the event I continue typing. As a highly desirable optional feature, the assistant should offer me an auto-completion key (e.g., the option key, or a menu item with a keyboard equivalent), which, when pressed, offers me a popup menu of possible completions for the word currently being typed, even when the completion is not uniquely identified.

The second required feature is auto-completion of syntactic elements. If I start a conditional by typing "if", my programmer's assistant should, when prompted by an auto-completion key, complete the conditional by inserting parentheses, braces, and an "else" clause, leaving something like this:

if () {
} else {
}

In this example, the cursor ought to be left between the parentheses, so that I can insert the conditional. You ought to provide some convenient way for me to move the cursor from the conditional (between the parentheses) to the TRUE branch (between the first pair of braces) to the FALSE branch (between the second pair of braces).

You would provide similar auto-completion for while loops, do loops, for loops:

while () {
}

for ( ; ; ) {
}

do {
} while ();

Other required auto-completions include case statements, struct declarations, enum declarations, and function declarations. Additional auto-completion features may be incorporated at your option. Other options (e.g., indentation styles) will also earn extra feature points.

A significant amount of extra consideration will be given to any solution that allow support for other languages, through use of a configuration file, provided such a configuration file is provided for C/C++ and at least one other language.

This will be a native PowerPC Challenge, using any of the following environments: CodeWarrior, REALbasic (version 3.2.1 or earlier), MetaCard (version 2.3.2 or earlier), Revolution (version 1.0), or Project Builder. You may use another development environment if I can arrange to obtain a copy - email progchallenge@mactech.com to check before you use something else. You can develop for Mac OS 9 or Mac OS X. This will be another Challenge based on a subjective evaluation of which entry best satisfies the required features, provides the most attractive set of optional features, and provides the best general usability and look-and-feel. Your solution should be a complete Macintosh application, so there is no prototype and no test code for this Challenge. Your submission should provide everything needed to build your application, as well as documentation of the features you have implemented, to ensure that I don't overlook anything.

Three Months Ago Winner

Only two people chose to enter the July DownNOut Challenge, and many-time champion Ernst Munter is once again our winner. The object of this Challenge was score as many points as possible while removing colored cells from a rectangular board. Cells are removed when they match the color of a selected cell and are connected to that cell via cells of the same color that are adjacent horizontally or vertically. The number of points earned for each move is the square of the number of cells removed, so there is an incentive to remove cells in the largest blocks possible. Solutions were required to display and update the game state after each move.

Ernst observes in his commentary that the time penalty discourages spending a lot of time searching alternative moves, so his solution relies on heuristics. His first step for each move is to identify all contiguous areas of cells (CreateAreas) and calculate their size. Next, he picks a target color for the move, with the objective of removing a large number of cells for that color in a later move. Ernst selects the color which has the smallest score based on the initial position of contiguous areas of cells, on the theory that removing the colors with larger initial contiguous areas will both score points and allow the smaller areas to coalesce. Once the target color is selected, Ernst tries to remove the smallest area of another color (GetSmallestArea1) that is nearest the top of the game board, and which has cells of the same color below it (a "shadow"). Failing that, he removes the smallest area of the target color. If no such areas are available, he chooses another target color and begins again.

I used a total of six test cases to evaluate the solutions, ranging in size from 8x25 to 20x40 cells, with 3, 4, or 5 cell colors. The table below lists, for each of the solutions submitted, the total number of points earned by removing cells over all test cases, the execution time in milliseconds, and the score. The score subtracts from the points earned a penalty of 1% for each millisecond of execution time, calculated individually for each test case. The table also lists the code size, data size, and programming language used for each entry. As usual, the number in parentheses after the entrant's name is the total number of Challenge points earned in all Challenges prior to this one.

Name Points Time Score
(msec)
Ernst Munter (758) 91632 236 25337
J. T. 52666 4536 -561692
Name Code Data Lang
Ernst Munter 10028 458 C++
J. T. 7192 340 C

Top Contestants ...

Listed here are the Top Contestants for the Programmer's Challenge, including everyone who has accumulated 20 or more points during the past two years. The numbers below include points awarded over the 24 most recent contests, including points earned by this month's entrants.

Rank Name Points
(24 mo)
1. Munter, Ernst 271
2. Rieken, Willeke 73
3. Saxton, Tom 71
4. Taylor, Jonathan 56
5. Wihlborg, Claes 49
6. Shearer, Rob 48
7. Maurer, Sebastian 38
10. Mallett, Jeff 20
11. Truskier, Peter 20
Name Wins Total Points
(24 mo)
Munter, Ernst 10 778
Rieken, Willeke 3 134
Saxton, Tom 2 189
Taylor, Jonathan 2 56
Wihlborg, Claes 2 49
Shearer, Rob 1 62
Maurer, Sebastian 1 108
Mallett, Jeff 1 114
Truskier, Peter 1 20

...and the Top Contestants Looking for a Recent Win

In order to give some recognition to other participants in the Challenge, we also list the high scores for contestants who have accumulated points without taking first place in a Challenge during the past two years. Listed here are all of those contestants who have accumulated 6 or more points during the past two years.

Rank Name Points Total
(24 mo) Points
8. Boring, Randy 32 144
9. Sadetsky, Gregory 22 24
12. Schotsman, Jan 14 14
13. Nepsund, Ronald 10 57
14. Day, Mark 10 30
15. Downs, Andrew 10 12
16. Desch, Noah 10 10
17. Duga, Brady 10 10
18. Fazekas, Miklos 10 10
19. Flowers, Sue 10 10
20. Strout, Joe 10 10
21. Nicolle, Ludovic 7 55
22. Hala, Ladislav 7 7
23. Leshner, Will 7 7
24. Miller, Mike 7 7

There are three ways to earn points: (1) scoring in the top 5 of any Challenge, (2) being the first person to find a bug in a published winning solution or, (3) being the first person to suggest a Challenge that I use. The points you can win are:

1st place 20 points
2nd place 10 points
3rd place 7 points
4th place 4 points
5th place 2 points
finding bug 2 points
suggesting Challenge 2 points

Here is Ernst's winning DownNOut solution:

DownNOut.cpp
Copyright © 2001
Ernst Munter

/*
Copyright © 2001, Ernst Munter, Kanata, ON, Canada.
 
      "Down-N-Out"
      
A solitaire game where colored stones are placed in a vertical grid of rows and
columns. Adjacent stones of the same color form groups which can be removed as
long as a group contains at least two stones. After each move, consisting of the 
removal of a group of stones from one or more columns, remaining stones slide down 
in each column. Empty columns are filled by shifting ajacent columns towards the 
center. The score is the sum of the squares of the number of stones in each move. 

The standard game will have three colors with 100 stones each, on a board of 10 rows 
and 30 columns.

Strategy
————
I select a target color and aim to make all the stones of of this color into a 
single contiguous group, by removing all groups of the other colors first.

As stones are removed, and others slide down, some groups may be separated and 
others newly formed. Hence, by careful play, and with some luck in picking the
right candidate, one can almost always assemble most of the stones of one color 
into one large group - when playing manually.

The time penalty in this challenge is 1% per millisecond of time. Hence, there is
not a lot of time for searches or backtracking. I have chosen to go with a few
heuristics which captures most of the stones in a single big move at the end (yielding 
a score of near 10,000), in about half of the games played. Just as often, however, 
it fails to provide a bridge, and the final pay-off is considerably less:

   ideally, 100 * 100 = 10,000, for a single move of all 100 stones of a color
   but 50 * 50 + 50 * 50 = 5,000 if two moves of 50 stones each are needed.
   
Display and Timing
—————————
The display of the board uses ColorQuickDraw PaintRect(), directly to the window.
A number of experiments with off-screen GWorlds did not result in any improvements.
The time to compute all the moves of a typical game is on the order of 2.5 msec, 
for a 2.5% penalty (display disabled); with the display on, the time increases
to 12.5msec overall. 
*/
#define NDEBUG
#include <assert.h>
#include <stdlib.h>
#include "DownNout.h"

#define SHOWCELLS 1   // May be set to 0 for timing without the display

enum {
   kMaxNumColors   = 18,   // 16 cell colors + white + black
   kMaxCellSize   = 8,   // dont draw them larger than this
   kMinCellSize   = 2      //           or smaller than this
};

const RGBColor myColors[kMaxNumColors]={
   {0xFF00,0xFF00,0xFF00},   //white
   {0xFFFF,0x0000,0x0000},   //red
   {0x0000,0xFFFF,0x0000},   //green
   {0x0000,0x0000,0xFFFF},   //blue
   
   {0xFFFF,0xFFFF,0x0000},   //yellow
   {0xFFFF,0x0000,0xFFFF},   //pink
   {0x0000,0xFFFF,0xFFFF},   //light blue-1
   
   {0xFFFF,0x9999,0x3333},   //brown-1
   {0xFFFF,0x3333,0x9999},   //light purple
   {0x9999,0xFFFF,0x3333},   //light green
   {0x9999,0x3333,0xFFFF},   //violet
   {0x3333,0xFFFF,0x9999},   //emerald
   {0x3333,0x9999,0xFFFF},   //light blue-2
   
   {0xCCCC,0x9999,0x6666},   //brown-2
   {0x6666,0xCCCC,0xCCCC},   //blue-3
   {0xCCCC,0x6666,0xCCCC},   //purple
   {0x5F00,0x5F00,0x5F00},   //gray
   {0x0000,0x0000,0x0000}   //black
};

static long gCellSize;   // final size of squares for drawing
static WindowPtr win;   // the window provided by caller during InitDownNOut()

typedef long MyCellColor;   // faster than CellColor=char

/*******************************************************************
/
/                     Class MyCell
/
/*******************************************************************/

class ColorSquare
// Defines the screen location and color of each cell, and draws it.
{
   Rect      rect;
   MyCellColor   color;
public:
   void Init(const Point& spt,const MyCellColor cc,long cellSize)

   {
      rect.top=spt.v+1;      // leave a 1-pixel white margin
      rect.left=spt.h+1;
      rect.bottom=spt.v+cellSize;
      rect.right=spt.h+cellSize;
      color=cc;
   }
   MyCellColor Color() const {return color;}
   
   void CopyColor(const MyCellColor xcolor) {color=xcolor;}
   
   void ClearColor() {color=0;}
   
   void Show()
   {
      RGBForeColor(myColors+color);
      PaintRect(&rect);
   }
};

/*******************************************************************
/
/                     Class MyCell
/
/*******************************************************************/

class MyCell:public ColorSquare
// Defines the logical position on the board, and a few flags 
{

private:
   long      tag;   // unique tag for each area
   short      row;   
   short      col;
   bool      seen;   // semaphore for recursive search
   bool      touch;   // indicates need to redraw this square
public:

   void Init(const Point& spot,const MyCellColor cc,
          long rrow,long ccol,long cellSize)
   {
      ColorSquare::Init(spot,cc,cellSize);
      row=rrow;
      col=ccol;
      tag=0;
      seen=false;
      touch=true;
   }

   long    Row() const {return row;}
   long    Col() const {return col;}
   
   void Tag(long t) {tag=t;}
   bool IsTagged(const long t) const {return (tag==t);}
   
   void See() {seen=true;}
   bool IsSeen() const {return seen;}
   void UnSee() {seen=false;}
   
   void Touch() {touch=true;}
   
   bool IsBlank() const {return (Color()==0);}
   
   void CopyBack(CellColor* b) {*b=Color();}
   
   void CopyColor(const MyCell* x) 
   { 
      if (Color() != x->Color())
      {
         touch=true;   
         ColorSquare::CopyColor(x->Color());
      } // else no change in color, no need to reassign or redraw
   }
   
   void ClearColor() {
      if (Color() != 0)
      {
         touch=true;
         ColorSquare::ClearColor();
      } // else no change in color, no need to reassign or redraw
   }
   
   int CompPosition(MyCell* x)
// Comparison member function for qsort
   {
      int dCol=col - x->col;// sort left to right
      if (dCol==0)
         return x->row - row;// and top to bottom
      return dCol;
   }
   
   void   Show()
// Draws the cell if it has changed
   {
      if (touch)
      {
         ColorSquare::Show();
         touch=false;

      }

   }

};

typedef MyCell* MyCellPtr;

static int CompCells(const void* a,const void* b)
// Comparison function for qsort
{
   MyCellPtr* ah=(MyCellPtr*)a;
   MyCellPtr* bh=(MyCellPtr*)b;
   MyCell* ap=*ah;
   MyCell* bp=*bh;
   return ap->CompPosition(bp);

}

/*******************************************************************
/
/                     Class Area
/
/*******************************************************************/

class Area
// An area is identified with one of its cells, and describes the size
// of the area, i.e. the number of contiguous equal-colored cells.
{
   MyCell*   ref;      // pointer to one cell in the area
   long   size;      // number of cells in area
public:
   void Init(MyCell* C,long areaSize)
   {
      ref=C;
      size=areaSize;
   }
   long Size() const {return size;}
   
   MyCellColor Color() const {return ref->Color();}
   
   MyCell* Cell() const {return ref;}
   
   void GetMove(short *moveRow,short *moveCol)
// The move is represented by the row/col coordinates of any area cell
   {
      *moveRow=ref->Row();
      *moveCol=ref->Col();
   }

};

typedef Area* AreaPtr;


/*******************************************************************
/
/                     Class Player
/
/*******************************************************************/

class Player
// Player is the main structure holding data from initialization through moves
// Player also implements almost all the game logic, calling upon MyCell and Area
// classes for utility functions.
{
private:
   long   nRows;
   long   nCols;
   long   nColors;

// My cells are stored in an array myBoard[col*nRows + row], arranged
//       to have sequential memory access for all cells in a column 

   MyCell*   myBoard;
   Area*   areas;
   long   numAreas;
// The cell list is allocated as a scratch pad for collecting the cells

//      to be removed at each move.

   MyCellPtr*   cellList;
   long   numInList;
// Move Number only serves as a source of unique tags for each move

   long    moveNr;
// A color is designated, to govern cell selection

   MyCellColor designatedColor;
   
public:
   Player(long boardSizeRows,long boardSizeCols,long numColors,

         const CellColor board[],WindowPtr wdw) :
      nRows(boardSizeRows),
      nCols(boardSizeCols),
      nColors(numColors),
      myBoard(
         new MyCell[sizeof(MyCell)*boardSizeRows*boardSizeCols]),
      areas(new Area[sizeof(Area)*(boardSizeRows*boardSizeCols)]),
      numAreas(0),
      cellList(
         new MyCellPtr[sizeof(MyCellPtr)*
                     (1+boardSizeRows*boardSizeCols/nColors)]),
      numInList(0),
      moveNr(0),
      designatedColor(0)
   {   
      win=wdw;

      long windowWidth=win->portRect.right-win->portRect.left;
      long windowHeight=win->portRect.bottom-win->portRect.top;
      long squareWidth=windowWidth/nCols;
      long squareHeight=windowHeight/nRows;

      gCellSize=(squareWidth < squareHeight) ? 
                              squareWidth : squareHeight;
      if (gCellSize>kMaxCellSize)
         gCellSize=kMaxCellSize;
      else if (gCellSize<kMinCellSize)
         gCellSize=kMinCellSize;
         
      InitCells(board);
      ShowRange(0,nCols);
   }
   
   ~Player()
   {
      delete [] cellList;
      delete [] areas;
      delete [] myBoard;
   }
   
   void InitCells(const CellColor board[])

// Copies the CellColors of board[] to MyCells in myBoard[]

//   while rearranging the row/column sequence to be more convenient

   {
      const CellColor* B=board;
      long cellSize=gCellSize;
      long   bottomRow=cellSize*(nRows-1);
      Point   spot={0,0};
      // will display row 0 at the bottom
      // will display col 0 at left
      for (long col=0;col<nCols;col++)
      {
         spot.v=bottomRow;
         for (long row=0;row<nRows;row++)
         {
            const CellColor* B=&board[row*nCols + col];
            MyCell* C=&myBoard[col*nRows + row];
            C->Init(spot,*B,row,col,cellSize);
            spot.v    -=   cellSize;
         }
         spot.h   +=   cellSize;
      }
   }
   
   void UpdateEvent(EventRecord theEvent)

// Checks validity of the event, and shows the entire board.

// Relies on caller to call BeginUpdate(..) and EndUpdate(..).

   {
      if ((theEvent.what==updateEvt) && 
               (win==(WindowPtr)theEvent.message))
      {
         // Touch all cells to ensure they are drawn
         for (int i=0;i<nRows*nCols;i++)
            myBoard[i].Touch();

         // Draw the board

         ShowRange(0,nCols);
      }
   }
   
   void RemoveCells(long row,long col,long numToRemove)

// Shifts one column down; row 0 is at the bottom

   {
      MyCell* dest=myBoard+col*nRows+row;
      MyCell* src=dest+numToRemove;
      MyCell* end=myBoard+(col+1)*nRows;
      while (src<end)
         (dest++)->CopyColor(src++);
      
      while (dest<end)
         (dest++)->ClearColor();
   }
   
   void ShowRange(long firstCol,long numColsToShow)

// Shows all cells which have been touched

   {
      if (!SHOWCELLS)
         return;
      GrafPtr   savePort;
      GetPort (&savePort);
      
      SetPort(win);      
      
      MyCell* C=myBoard + firstCol*nRows;
      for (int i=0;i<numColsToShow*nRows;i++)
         (C++)->Show();
      
      SetPort (savePort);
    }
    
   Area* GetSmallestArea1(const MyCellColor avoidColor)

// Returns the smallest area, not of "avoidColor", nearest the top, and which has a 

// shadow. 

   {
      long smallestSize=nCols*nRows;
      Area* bestArea=0;
      long topRow=-1;
      for (int i=0;i<numAreas;i++)
      {
         Area* A=&areas[i];
         if    (    (A->Size() <= smallestSize)
            &&   (A->Color() != avoidColor)
            && (A->Cell()->Row() > topRow) 
            &&   (Shadow(A->Cell(),A->Color()))
            )
         {
            bestArea=A;
            smallestSize=A->Size();
            topRow=A->Cell()->Row();
         }
      }
      UnSeeAll();
      return bestArea;
   }
   
   bool Shadow(MyCell* C,const MyCellColor theColor) 

// Returns true if the area containing C is in the "shadow" of a cell of theColor,

// i.e. there is at least one cell of theColor above the area. 

   {
      if (C->IsSeen())
         return false;
      long row=C->Row();
      long col=C->Col();
      C->See();
      if (Shade(C+1,C-row+nRows,theColor))
         return true;
         
      if ((row>0) 
         && ((-1)[C].Color()==theColor) 
         && Shadow(C-1,theColor))
            return true; 
            
      if ((row<nRows-1) 
         && ((1)[C].Color()==theColor)
         && Shadow(C+1,theColor))
            return true; 
            
      if ((col>0) 
         && ((-nRows)[C].Color()==theColor)
         && Shadow(C-nRows,theColor))
            return true; 
            
      if ((col<nCols-1)
         && ((nRows)[C].Color()==theColor)
         && Shadow(C+nRows,theColor))
            return true; 
         
      return false;
   }
   
   bool Shade(MyCell* C,MyCell* end,const MyCellColor theColor)

// Checks the column of C and above.

// Returns true if it encounters a cell of theColor. 

   {
      while ((C<end) && (C->Color()!=0))
      {
         if ((C->Color()!=theColor))
            return true;
         C++;
      }
      return false;
   }
   
   void UnSeeAll()
// Clears all "seen" flags.
   {
      for (long i=0;i<nRows*nCols;i++)
         myBoard[i].UnSee();
   }
   

   Area* GetSmallestArea2(const MyCellColor chosenColor)

// Returns the smallest area of the chosen color.

   {

      long smallestSize=nCols*nRows;
      Area* bestArea=0;
      long bottomRow=nRows;
      for (int i=0;i<numAreas;i++)
      {
         Area* A=&areas[i];
         if   (    (A->Size() < smallestSize) 
            &&   (A->Color() == chosenColor)
            )
         {
            bestArea=A;
            smallestSize=A->Size();
         }
      }
      return bestArea;
   }
   
   long MeasureArea(MyCell* C,const MyCellColor theColor)

// All cells connected to C, and of the same color, are counted and tagged.

// Recursively collects all cells of one area and returns the size of the area.

   {   

      C->Tag(moveNr);   // uses the current move number as a unique tag

      long areaSize=1;
      
      long row=C->Row();
      long col=C->Col();
      
      if ((row>0) 
         && ((-1)[C].Color()==theColor) 
         && !(-1)[C].IsTagged(moveNr))
            areaSize+=MeasureArea(C-1,theColor);    
      
      if ((row<nRows-1) 
         && ((1)[C].Color()==theColor) 
         && !(1)[C].IsTagged(moveNr))
            areaSize+=MeasureArea(C+1,theColor);       
      
      if ((col>0) 
         && ((-nRows)[C].Color()==theColor) 
         && !(-nRows)[C].IsTagged(moveNr))
            areaSize+=MeasureArea(C-nRows,theColor);        
      
      if ((col<nCols-1) 
         && ((nRows)[C].Color()==theColor) 
         && !(nRows)[C].IsTagged(moveNr))
            areaSize+=MeasureArea(C+nRows,theColor);       
      
      return areaSize;
   }
      
   long CreateAreas()

// The board is scanned and all contiguous areas are identified.

   {
      long num=0;
      MyCell* C0=myBoard;
      for (long col=0;col<nCols;col++,C0+=nRows)
      {
         MyCell* C=C0;
         for (long row=0;row<nRows;row++,C++)
         {
            if (C->IsTagged(moveNr))
               continue;   
            
            if (C->IsBlank())   // reached top of active row
               break;
               
            long areaSize=MeasureArea(C,C->Color());
            if (areaSize >= 2)
               areas[num++].Init(C,areaSize);
         }

      }   

      return num;
   }
   
   long Play(CellColor board[],short *moveRow,short *moveCol)

// The main Play() function, called once per move.

// Plays one move and returns the number of cells removed.

   {   
      moveNr++;
      
// Identify all areas.
      numAreas=CreateAreas();
      
      if (numAreas==0) // game over !
         return 0;

// Ensure we have a target color.

choose_a_color:      
      if (designatedColor==0)
         designatedColor=ChooseColor();
      
// First choice: remove a small area of another color.
        Area* area=GetSmallestArea1(designatedColor);
                              //minimum area of unreserved color
      if (0==area)
      {
// Second choice: remove smallest area of the chosen color.
         area=GetSmallestArea2(designatedColor);
                           //minimum area of reserved color
         if (0==area)
         {
// Third choice: find a new color.
            designatedColor=0;
            goto choose_a_color;
         }
      }
      
// .. and do the removal.
      long numCellsRemoved=Execute(area,board,moveRow,moveCol);
      
      return numCellsRemoved;
   }
   
   const MyCellColor ChooseColor()

// Chooses a color which we hope can be the color of a large area.

// The heuristic is to first remove all areas of other colors which are already more 
// coherent. This should then allow the smaller areas and single cells of the chosen 
// color to coalesce and form a larger single area.

   {
      long score[kMaxNumColors];
      for (int i=1;i<=nColors;i++)
         score[i]=0;
      for (int i=0;i<numAreas;i++)
      {
         long color=areas[i].Color();
         long size=areas[i].Size();
         score[color]+=size*size;
      }
      
      long lowestScore=nRows*nRows*nCols*nCols;
      MyCellColor chosenColor=0;
      for (int i=1;i<=nColors;i++)
      {
          if ((score[i] > 0) && (score[i] < lowestScore))
         {
            lowestScore=score[i];
            chosenColor=i;
         }
      }
      
      return chosenColor;
   }
   
   long Execute(Area* area,CellColor board[],
                     short *moveRow,short *moveCol)
// Removes the selected area and returns its size.
   {
      area->GetMove(moveRow,moveCol);
      numInList=0;
      MyCellColor theColor=area->Color();
      
// Collect all cells of the area into a single list
      MakeList(area->Cell(),theColor);
      
      assert(numInList==area->Size());
      
// Sort the list, so that whole clumns can be removed if possible
      qsort(cellList,numInList,sizeof(MyCellPtr),CompCells);
      
// cells in list are sorted by col,row
// we'll remove cells by col, row, num rows in col
      long minCol=nCols;
      long maxCol=-1;
      for (int i=0;i<numInList;i++)
      {
         MyCell* C=cellList[i];
         long row=C->Row();
         long col=C->Col();
         long n=1;
         // count number of contiguous cells in column for removal
         for (int k=i+1;k<numInList;k++,n++)
         {
            long nextRow=row-1;
            if ((cellList[k]->Col() != col) || 
                        (cellList[k]->Row() != nextRow))
               break;
            
            i++;
            row=nextRow;
         }
         assert(row>=0);
         assert(row+n<=nRows);
         assert(col>=0);
         assert(col<nCols);
         RemoveCells(row,col,n);

// Remember column range
         if (maxCol < col) maxCol=col;
         if (minCol > col) minCol=col;
      }
      
      assert(maxCol<nCols);
      assert(minCol>=0);

// If any empty cols result, move cols towards center, extend range
//      .. from the right

      for (long col=maxCol;(col>=(nCols-nCols/2)) && 
                        (col>=minCol);col—)
      {
         if (IsEmptyColumn(col))
         {
            ShiftLeft(col);
            maxCol=nCols-1;
         }
      }
//      .. and from the left
      for (long col=minCol;(col<=nCols/2) && (col<=maxCol);col++)
      {
         if (IsEmptyColumn(col))
         {
            ShiftRight(col);
            minCol=0;
         }
      }

// Display all touched cells in range
      ShowRange(minCol,maxCol-minCol+1);

// Let the caller know what happened: update his board[]
      CopyBackBoard(board,minCol,maxCol-minCol+1);

//    .. and return the number of cells removed.

      return numInList;
   }
   
   void CopyBackBoard(CellColor board[],long firstCol,long numColsToShow)

// Copies the cell colors of myBoard[] to the callers board[]

// Note the different array indexing.

   {
      MyCell* C=&myBoard[firstCol*nRows];
      for (long col=firstCol;col<firstCol+numColsToShow;col++)
      {
         for (long row=0;row<nRows;row++,C++)
         {
            CellColor* B=&board[row*nCols + col];
            C->CopyBack(B);
         }
      }
   }
   
   bool IsEmptyColumn(long col)
// Returns true if the first cell in a column is blank (white)
   {
      return (myBoard[col*nRows].IsBlank());
   }
   
   void ShiftRight(long destCol)
// Shifts all columns left of destCol to the right by one position
   {
      long minCol=0;
      for (;minCol<destCol;minCol++)
         if (!IsEmptyColumn(minCol))
            break;
      for (long srcCol=destCol-1;srcCol>=minCol;srcCol—,destCol—)
      {
         CopyColumn(destCol,srcCol);
      }
      ClearColumn(minCol);
   }
   
   void ShiftLeft(long destCol)
// Shifts all columns right of destCol to the left by one position
   {
      long maxCol=nCols-1;
      for (;maxCol>destCol;maxCol—)
         if (!IsEmptyColumn(maxCol))
            break;
      for (long srcCol=destCol+1;srcCol<=maxCol;srcCol++,destCol++)
      {
         CopyColumn(destCol,srcCol);
      }
      ClearColumn(maxCol);
   }
   
   void CopyColumn(long destCol,long srcCol)
// Copies one column from bottom row up, stopping when both are blank 
   {
      MyCell* dest=&myBoard[destCol*nRows];
      MyCell* src=&myBoard[srcCol*nRows];
      for (long row=0;row<nRows;row++)
      {
         if ((dest[row].IsBlank()) && (src[row].IsBlank()))
            break;
         dest[row].CopyColor(src+row);
      }
   }
   
   void ClearColumn(long col)
// Clears a column from bottom row up, stopping at first blank row
   {
      MyCell* dest=&myBoard[col*nRows];
      MyCell* end=dest+nRows;
      while (dest<end)
      {
         if (dest->IsBlank())
            break;
         (dest++)->ClearColor();
      }
   }
   
   void MakeList(MyCell* C,const MyCellColor theColor)
// Scans an area recursively, and puts a reference to each cell into cellList.
   {
      C->Tag(0);
      cellList[numInList++]=C;
      
      long row=C->Row();
      long col=C->Col();
      if ((row>0) 
         && ((-1)[C].Color()==theColor) 
         && !(-1)[C].IsTagged(0))
            MakeList(C-1,theColor); 
            
      if ((row<nRows-1) 
         && ((1)[C].Color()==theColor) 
         && !(1)[C].IsTagged(0))
            MakeList(C+1,theColor);
             
      if ((col>0) 
         && ((-nRows)[C].Color()==theColor) 
         && !(-nRows)[C].IsTagged(0))
            MakeList(C-nRows,theColor);
             
      if ((col<nCols-1) 
         && ((nRows)[C].Color()==theColor) 
         && !(nRows)[C].IsTagged(0))
            MakeList(C+nRows,theColor); 
   }
};

static Player*    P=0;

/*******************************************************************
/
/                  External Functions
/
/*******************************************************************/

void InitDownNOut(
 short boardSizeRows, /* number of rows in the game */
 short boardSizeCols, /* number of columns in the game */
 short numColors,   /* number of colors in the game */
 const CellColor board[],
  /* board[row*boardSizeCols + col] is color of cell at [row][col] */
 WindowPtr gameWindow
  /* window where results of your moves should be displayed */
)
{
   if ((boardSizeRows>0) 
      && (boardSizeCols>0) 
      && (numColors>=1)
      && (numColors+2<=kMaxNumColors) )
   P=new Player(boardSizeRows,boardSizeCols,numColors,board,gameWindow);
}

void HandleUpdateEvent(EventRecord theEvent)
{
   if (P) P->UpdateEvent(theEvent);
}

Boolean /* able to play */ PlayOneDownNOutMove(
   long score,         /* points earned prior to this move */
   CellColor board[],   /* board[row*boardSizeCols + col] is color of cell at [row][col] */
   short *moveRow,      /* return row of your next move */
   short *moveCol,      /* return col of your next move */
   long *numberOfCellsRemoved   /* self explanatory */
)
{
#pragma unused(score)
   if (P)
   {
      long numCellsRemoved=
         P->Play(board,moveRow,moveCol);
      
      if (numCellsRemoved>0)
      {
         *numberOfCellsRemoved=numCellsRemoved;
         return true;
      }
   }
   *numberOfCellsRemoved=0;
   return false;
}

void TermDownNOut(void) 
{
   delete P; 
// Deletes the only visible variable which in turn destroys its allocated data members.
   P=0;
}
 
AAPL
$99.76
Apple Inc.
+2.09
MSFT
$44.08
Microsoft Corpora
+0.45
GOOG
$520.84
Google Inc.
+9.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

TechTool Pro 7.0.5 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PDFKey Pro 4.0.2 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Yasu 2.9.1 - System maintenance app; per...
Yasu was originally created with System Administrators who service large groups of workstations in mind, Yasu (Yet Another System Utility) was made to do a specific group of maintenance tasks... Read more
Hazel 3.3 - Create rules for organizing...
Hazel is your personal housekeeper, organizing and cleaning folders based on rules you define. Hazel can also manage your trash and uninstall your applications. Organize your files using a... Read more
Autopano Giga 3.7 - Stitch multiple imag...
Autopano Giga allows you to stitch 2, 20, or 2,000 images. Version 3.0 integrates impressive new features that will definitely make you adopt Autopano Pro or Autopano Giga: Choose between 9... Read more
MenuMeters 1.8 - CPU, memory, disk, and...
MenuMeters is a set of CPU, memory, disk, and network monitoring tools for Mac OS X. Although there are numerous other programs which do the same thing, none had quite the feature set I was looking... Read more
Coda 2.5 - One-window Web development su...
Coda is a powerful Web editor that puts everything in one place. An editor. Terminal. CSS. Files. With Coda 2, we went beyond expectations. With loads of new, much-requested features, a few... Read more
Arq 4.6.1 - Online backup to Google Driv...
Arq is super-easy online backup for the Mac. Back up to your own Google Drive storage (15GB free storage), your own Amazon Glacier ($.01/GB per month storage) or S3, or any SFTP server. Arq backs up... Read more
Airfoil 4.8.10 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
Apple iMovie 10.0.6 - Edit personal vide...
With an all-new design, Apple iMovie lets you enjoy your videos like never before. Browse your clips more easily, instantly share your favorite moments, and create beautiful HD movies and Hollywood-... Read more

Latest Forum Discussions

See All

This Week at 148Apps: October 13-17, 201...
Expert App Reviewers   So little time and so very many apps. What’s a poor iPhone/iPad lover to do? Fortunately, 148Apps is here to give you the rundown on the latest and greatest releases. And we even have a tremendous back catalog of reviews; just... | Read more »
Angry Birds Transformers Review
Angry Birds Transformers Review By Jennifer Allen on October 20th, 2014 Our Rating: :: TRANSFORMED BIRDSUniversal App - Designed for iPhone and iPad Transformed in a way you wouldn’t expect, Angry Birds Transformers is a quite... | Read more »
GAMEVIL Announces the Upcoming Launch of...
GAMEVIL Announces the Upcoming Launch of Mark of the Dragon Posted by Jessica Fisher on October 20th, 2014 [ permalink ] Mark of the Dragon, by GAMEVIL, put | Read more »
Interview With the Angry Birds Transform...
Angry Birds Transformers recently transformed and rolled out worldwide. This run-and-gun title is a hit with young Transformers fans, but the ample references to classic Transformers fandom has also earned it a place in the hearts of long-time... | Read more »
Find Free Food on Campus with Ypay
Find Free Food on Campus with Ypay Posted by Jessica Fisher on October 20th, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »
Strung Along Review
Strung Along Review By Jordan Minor on October 20th, 2014 Our Rating: :: GOT NO STRINGSUniversal App - Designed for iPhone and iPad A cool gimmick and a great art style keep Strung Along from completely falling apart.   | Read more »
P2P file transferring app Send Anywhere...
File sharing services like Dropbox have security issues. Email attachments can be problematic when it comes to sharing large files. USB dongles don’t fit into your phone. Send Anywhere, a peer-to-peer file transferring application, solves all of... | Read more »
Zero Age Review
Zero Age Review By Jordan Minor on October 20th, 2014 Our Rating: :: MORE THAN ZEROiPad Only App - Designed for the iPad With its mind-bending puzzles and spellbinding visuals, Zero Age has it all.   | Read more »
Hay Ewe Review
Hay Ewe Review By Campbell Bird on October 20th, 2014 Our Rating: :: SAVE YOUR SHEEPLEUniversal App - Designed for iPhone and iPad Pave the way for your flock in this line drawing puzzle game from the creators of Worms.   | Read more »
My Very Hungry Caterpillar (Education)
My Very Hungry Caterpillar 1.0.0 Device: iOS Universal Category: Education Price: $3.99, Version: 1.0.0 (iTunes) Description: Care for your very own Very Hungry Caterpillar! My Very Hungry Caterpillar will captivate you as he crawls... | Read more »

Price Scanner via MacPrices.net

2013 15-inch 2.0GHz Retina MacBook Pro availa...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
Updated iPad Prices
We’ve updated our iPad Air Price Tracker and our iPad mini Price Tracker with the latest information on prices and availability from Apple and other resellers, including the new iPad Air 2 and the... Read more
Apple Pay Available to Millions of Visa Cardh...
Visa Inc. brings secure, convenient payments to iPad Air 2 and iPad mini 3as well as iPhone 6 and 6 Plus. Starting October 20th, eligible Visa cardholders in the U.S. will be able to use Apple Pay,... Read more
Textkraft Pocket – the missing TextEdit for i...
infovole GmbH has announced the release and immediate availability of Textkraft Pocket 1.0, a professional text editor and note taking app for Apple’s iPhone. In March 2014 rumors were all about... Read more
C Spire to offer iPad Air 2 and iPad mini 3,...
C Spire on Friday announced that it will offer iPad Air 2 and iPad mini 3, both with Wi-Fi + Cellular, on its 4G+ LTE network in the coming weeks. C Spire will offer the new iPads with a range of... Read more
Belkin Announces Full Line of Keyboards and C...
Belkin International has unveiled a new lineup of keyboard cases and accessories for Apple’s newest iPads, featuring three QODE keyboards and a collection of thin, lightweight folios for both the... Read more
Verizon offers new iPad Air 2 preorders for $...
Verizon Wireless is accepting preorders for the new iPad Air 2, cellular models, for $100 off MSRP with a 2-year service agreement: - 16GB iPad Air 2 WiFi + Cellular: $529.99 - 64GB iPad Air 2 WiFi... Read more
Price drops on refurbished Mac minis, now ava...
The Apple Store has dropped prices on Apple Certified Refurbished previous-generation Mac minis, with models now available starting at $419. Apple’s one-year warranty is included with each mini, and... Read more
Apple refurbished 2014 MacBook Airs available...
The Apple Store has Apple Certified Refurbished 2014 MacBook Airs available for up to $180 off the cost of new models. An Apple one-year warranty is included with each MacBook, and shipping is free.... Read more
Refurbished 2013 MacBook Pros available for u...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available starting at $929. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros (4GB RAM/... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** As businesses discover the power of Apple computers and mobile devices, it's your job - as a Solutions Engineer - to show them how to introduce these Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.