TweetFollow Us on Twitter

Apr 98 Challenge

Volume Number: 14 (1998)
Issue Number: 4
Column Tag: Programmer's Challenge

Apr 98 - Programmer's Challenge

by Bob Boonstra, Westford, MA

Mancala

A stocking stuffer from this past Christmas provided the inspiration for this month's Challenge. Santa gave me a two player travel game called Mancala which might provide some amusement the next time I travel by car or by plane, provided the ride is smooth enough to keep the small stones inside the bowls of the game board. I thought it might make for an interesting Challenge tournament.

The basic Mancala game consists of a board with 14 hollowed-out bowls arranged in an oval form, one large bowl at each end of the board, and six smaller bowls facing each of two players seated opposite one another. Each player "owns" the large bowl, or "mancala", positioned to his right, and the six small bowls closest to him. The game starts with each small bowl containing four stones. The game begins with the first player picking up all of the stones in one of his small bowls, dropping one stone in the bowl to the right, the second stone in the second bowl on the right, continuing around the board in counterclockwise fashion until the stones he picked up are gone. The second player then picks up the stones in one of his small bowls, drops them one at a time in the bowls to the right, etc. The game ends when one player cannot move (i.e., no stones remain in that player's small bowls). The winner is the player with the most stones in his mancala. There are a number of variations to the game, and the specific restrictions on our Mancala Challenge tournament are explained below.

The prototype for the code you should write is:

#if defined(__cplusplus)
extern "C" {
#endif

Boolean Mancala(
  long board[],        /* on entry, board[i] is number of stones in bowl i */
                       /* on exit, board reflects the results of your move */
  const long boardSize,  /* number of bowls in the board, including mancalas */
  void *privStorage,     /* pointer to 1MB of storage for your use */
  const Boolean newGame, /* true for your first move of a game */
  const Boolean playerOne,/* true when you are the first player */
  long *bowlPlayed,      /* return the number of the bowl you played from */
  long *directionPlayed  /* return 1 if you played counter-clockwise, */
                         /* return -1 if you played clockwise */
);

#if defined(__cplusplus)
}
#endif

Each time your Mancala routine is called, you will be provided with a board[] array that indicates the number of stones in each bowl, including the Mancalas, at the beginning of your turn. The boardSize parameter will indicate the number of bowls in the board - in the standard Mancala game, this would be 14, but in our Challenge it might be any even number between 8 and 32, inclusive. The mancala for the first player will be board[0], while the mancala for the second player will be board[boardSize/2]. You will also be provided a pointer privStorage to 1MB of storage, preinitialized to zero, for each of your moves in a single game. For your first move of a game, newGame will be TRUE, otherwise newGame will be false. If you are the first player, playerOne will be TRUE for each of your moves, otherwise playerOne will be FALSE. You should return the index of the bowl you played from in bowlPlayed, and you should return the direction you chose to move in directionPlayed. You should also update your view of the number of stones in each bowl in board[].

There are a number of rule variations for Mancala. We will play with the following additions to the standard rules:

  • the board will contain between eight and 32 bowls, instead of the standard 14.
  • at the beginning of the game, each small bowl will have between two and 16 stones (instead of the standard four), with the same number in each bowl.
  • players do not drop stones into their opponent's mancalas.
  • players may choose to move either counter-clockwise or clockwise on a given move.
  • if a player drops the last stone into his mancala, he gets to move again (my test code will call your Mancala routine again).
  • if a player drops the last stone into one of the empty bowls (board[i]) on his side of the board, he takes that stone, plus all the stones in his opponent's bowl directly across from his bowl (board[boardSize-i]) and places them in his mancala.
  • the game ends when one player has no stones in any of his small bowls and cannot move. The other player then places all remaining stones from his small bowls into his mancala.

At the end of the game, each player will be credited with one point for each stone in his mancala, minus one point for each 100ms of cumulative execution time. The Challenge winner will be the entry that accumulates the most points in a round-robin tournament where each entry competes against each other entry twice for each set of game parameters, once playing first, and once playing second.

This will be a native PowerPC Challenge, using the latest CodeWarrior environment. Solutions may be coded in C, C++, or Pascal.

Three Months Ago Winner

Congratulations once again to Ernst Munter (Kanata, Ontario) for submitting the fastest entry to the January Cell Selection Challenge. Readers were invited to implement a C++ CellSelection class, including methods to add one selection to another, remove one selection from another, invert a selection, count the number of active cells in a selection, and determine if two selections were equal. A dual-processor 8500/2x200 was used to test this Challenge, and contestants were free to take advantage of the multiple processors, either through the Apple/Daystar Multiprocessing API, or by programming for BeOS and taking advantage of the symmetric multiprocessing features of that operating system.

Or so I thought when I structured the problem. As it turned out, of the four solutions submitted, only one took advantage of the multiprocessor opportunity. I'll discuss the use of multiprocessing in that solution later in the article. Ernst based his solution on the "vixel" data structure he used to win the Intersecting Rectangle Challenge of two years ago. His code is well-commented, so I'll let his solution speak for itself, except to point out that one other entry made reference to the "vixel" approach. It's nice to see readers put winning code from the past to good (and efficient) use.

The table below lists the total execution time in milliseconds for all test cases, as well as execution times for five individual test cases. It also lists code size, data size, and the number of processors used for each entry. The number in parentheses after the entrant's name is the total number of Challenge points earned in all Challenges to date prior to this one. The entries marked with an asterisk are those which did not complete one or more test cases. Test times in italics are extrapolated from partial test cases that were successfully completed. (See table 1).

Ulf Schröder's entry was the only one to attempt to use both of the processors available in the test machine. I tested a version of Ulf's entry modified to use only one processor, but the results were not much different, suggesting that either the CellSelection problem is not amenable to partitioning, or that Ulf's technique for doing so didn't have much affect for the particular test cases I used.

This Challenge was intended to be about multiprocessing, so it is worth spending a minute on how Ulf tried to take advantage of it. The first step was to determine how many processors were available and to create a task entry and a pair of semaphores for each processor:

  if (!MPLibraryIsLoaded())
    gProcessors = 1;
  else
    gProcessors = MPProcessors();
  
  // Create the tasks if more than one processor
  if (gProcessors > 1)
  {
    OSErr err;
      .....
    for (int32 i = 0; i < GPROCESSORS - 1; ++I)
    {
      ERR = MPCREATESEMAPHORE(1, 0,     
        &GTASKDATA[I].MSTARTSEMAPHORE);
      IF (ERR != NOERR) THROW ERR;
        
      ERR = MPCREATESEMAPHORE(1, 0,
        &GTASKDATA[I].MFINISHEDSEMAPHORE);
      IF (ERR != NOERR) THROW ERR;
        
      ERR = MPCREATETASK(
          TASK, &GTASKDATA[I], 0, GTERMINATIONQUEUE,
          0, 0, 0, &GTASKDATA[I].MTASKID);
      IF (ERR != NOERR) THROW ERR;
    }

This step is done once, at initialization time. Then later, when the code determines that it has a problem worth partitioning, it divides the problem, assigns one piece to another task (or tasks, in the general case), signals the other task to begin work, solves the remaining piece of the problem, and then waits for the other task to complete it's portion.

    IF (GPROCESSORS > 1 && length > kMinLengthForMP)
    {  
      uint32 mid = length / 2;
      .....
      DoRemove doRemove(area, restEnd);
      DoRemove doRemove1(area, rest1End);

      gTaskData->mBegin = mAreas.begin() + mid;
      gTaskData->mEnd = mAreas.end();
      gTaskData->mNewEnd = gTaskData->mEnd;
      gTaskData->mFunction = &doRemove1;
      
      // Start the other task
      MPSignalSemaphore(gTaskData->mStartSemaphore);

      // Do my part of the job
      AreaList::iterator newEnd =
        remove_if(
          mAreas.begin(),
          mAreas.begin() + mid,
          doRemove);
      
      // Wait for other task
      MPWaitOnSemaphore(gTaskData->mFinishedSemaphore,
        kDurationForever);
      .....
    }

For further information, there is an introduction to multiprocessing on the Mac in the March, 1996, issue of MacTech Magazine, or you can visit Apple's web site to obtain MultiProcessing API in the SDK, including some sample code.

Top 20 Contestants

Here are the Top Contestants for the Programmer's Challenge, including everyone who has accumulated more than 10 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
  1.  Munter, Ernst         218
  2.  Boring, Randy          73
  3.  Cooper, Greg           61
  4.  Lewis, Peter           51
  5.  Mallett, Jeff          50
  6.  Nicolle, Ludovic       44
  7.  Murphy, ACC            34
  8.  Gregg, Xan             28
  9.  Antoniewicz, Andy      24
 10.  Day, Mark              20
 11.  Higgins, Charles       20
 12.  Hostetter, Mat         20
 13.  Rieken, Willeke        20
 14.  Studer, Thomas         20
 15.  Hart, Alan             14
 16.  O'Connor, Turlough     14
 17.  Picao, Miguel Cruz     14

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            5th place  2 points
2nd place  10 points          finding bug  2 points
3rd place  7 points  suggesting Challenge  2 points
4th place  4 points

Here is Ernst's winning solution to the CellSelection Challenge:

Cells.h
© 1998 Ernst Munter

/*
      "Cell Selection"

This file is a C++ header file containing the CellSelection class, as well as a number of auxiliary structs and classes.

The purpose of the CellSelection class is to contain a set of cells in a 2-D world. Cells can be added and manipulated in groups represented as sets of cells, called Areas.

Solution Strategy

The overall idea is the same as the one I used in the "Intersecting Rectangles" challenge (solution in MacTech of Apr 96).

Cells are similar to black-and-white pixels, and any area of all-black (off) or all-white (on) pixels can be represented by a single bit and the 4 edge coordinates. I had called such a group of pixels a "vixel".

The CellSelection class maintains two sets of coordinates, rows and columns, and a bit map of vixels.

The empty selection starts out with a single (off) vixel, covering the area defined by the range of 32-bit integers (left=-2147483648,top=-2147483648,right=2147483647, bottom=2147483647).

As areas are added or removed, missing coordinates are inserted and the total area becomes further and further divided into sub-areas.

Coordinate sets are stored in trees to facilitate easy lookup. In addition, they are linked in linear lists to make it easier to traverse a span of coordinates corresponding to the edges of a given area which may be represented by a rectangular block of many sub-areas of vixels.

Memory Management

As row and column coordinates are added, each is allocated by "new". Each row also holds a pointer to "vixels" which are allocated with each row as needed. The default amount of vixel bits per row is set to 512. If more vixels are needed as the CellSelection grows, rows are expanded in increments of 512 bits. The bit map is not sorted right to left; rather, each column struct contains an index to the bit-position in the vixel array. The bits are allocated from the vixels arrays in the order of arrival with the method calls.

All calls to "new" are in try/catch blocks in order to allow the test program to fail gracefully if we should run out of memory.

Optimisations

Basically none.

Memory, rows and columns, get allocated as needed, but are only deleted when the CellSelection is destroyed. This will probably slow things down as the vixel map gets more and more fragmented in large selections.

A future improvement could be a garbage collector which detects when adjacent rows or columns are identical and can be merged.

Alternatively, CellSelections could be kept in a "normal" state during each operation by avoiding unnecessary splits of coordinates, and detection of pairs that can be merged.

Extras

I have added some public methods to the CellSelection class to simplify testing:

int CellSelection::Width()  
int CellSelection::Height()
  return the width and height of the vixel map
  
void CellSelection::ResetTestAreas()
bool CellSelection::NextTestArea(Area* a)
  permit stepping through the vixel map and identify
  each sub-area that contains a block of cells

I have also added a method to the Area struct to test for empty areas according to the definition.

Clarifications

Methods with return type "bool" (except EqualSelected()) return false only if we run out of memory. They return true in all other cases, including calls with empty areas.

The class makes no assumptions which could restrict the range of areas. Specifically, an area with a right or bottom coordinate of 2147483647 will be handled correctly, i.e. we do not need a value 1 greater than the highest value coordinate of an area. */

#include <STRING.H>
// needed for memcpy and memset

#if __dest_os == __be_os
#include <SUPPORTDEFS.H>
#else
typedef long int32;
typedef unsigned long uint32;
#endif

#define EXTRA_FOR_TESTING 1

static const enum ProgConsts{
  kIncrementBits=512,
  kNegInfinity=0x80000000L,
  kPosInfinity=0x7FFFFFFFL
} 
// the following line avoids a compiler warning in CW-PRO2
Consts(kNegInfinity);

Area 
struct Area {
  int32    left,top,right,bottom;
    /* Area coordinates are inclusive.  {2,2,3,4} includes 6 cells. */
  const bool IsEmpty() const {  
    /* Any area with left>right or top>bottom is empty. */
    return ((left>right) | (top>bottom));
  }    
};


Node 
struct Node {
  int32    lo;
  Node*    nextNode;
  Node*   leftNode;
  Node*   rightNode;
  int     bal;
  Node(int32 x) {
    lo=x;
    leftNode=rightNode=nextNode=0;
    bal=0;
  }
  int32 Limit() const {  
    return (nextNode)?nextNode->lo-1:kPosInfinity;
  }
  uint32 Slice(int32 xlo,int32 xhi) const {
    int32 upperLimit=Limit();
    return 1+(xhi<UPPERLIMIT?XHI:UPPERLIMIT)-(XLO>lo?xlo:lo);
  }
};  

Row:Node
struct Row:Node{
  int    size;      // number of bytes allocated
  char*    vixels;  // 1 bit per vixel
  Row(int32 x):Node(x){
    size=kIncrementBits/8;
    try {vixels=new char[size];}
    catch (...) {vixels=0;return;}
    memset(vixels,0,size);
  }
  Row(Row* rp):Node(rp->lo){
    size=rp->size;
    try {vixels=new char[size];}
    catch (...) {vixels=0;return;}
    memcpy(vixels,rp->vixels,size);
  }
  ~Row(){delete[] vixels;}
  Row* Next() const {return (Row*)(nextNode);}
  bool Stretch(uint32 index,uint32 width) {
//if necessary, we replace this row with a wider row
    if (width >= size*8) {
      int newSize=size+kIncrementBits/8;
      char* newVixels;
      try{newVixels=new char[newSize];}
      catch(...){return false;}
      memcpy(newVixels,vixels,size);
      memset(newVixels+size,0,kIncrementBits/8);
      delete vixels;
      size=newSize;
      vixels=newVixels;
    }  
    if (Vixel(index)) SetVixel(width);//else already 0;
    return true;
  }
#define MEMBER vixels[index>>3]
#define BIT  (1L<<(INDEX&7))
  INT VIXEL(UINT32 INDEX) CONST {RETURN MEMBER & BIT;}
  VOID CLEARVIXEL(UINT32 INDEX) {MEMBER &= ~BIT;}
  VOID SETVIXEL(UINT32 INDEX)   {MEMBER |= BIT;}
  VOID INVERTVIXEL(UINT32 INDEX){MEMBER ^= BIT;}
#UNDEF MEMBER
#UNDEF BIT  
  BOOL INITFAILED() CONST {RETURN (VIXELS==0);}
};

COL:NODE
STRUCT COL:NODE {
  UINT32  INDEX;// BIT NUMBER IN EVERY ROW OF VIXELS
  COL(INT32 XLEFT,UINT32 XINDEX):
  NODE(XLEFT){INDEX=XINDEX;}
  COL* NEXT() CONST {RETURN (COL*)(NEXTNODE);}
};

TREE 
CLASS TREE {
// BASED ON AVL BALANCED BINARY TREE, SEE:
// "ALGORITHMS AND DATA STRUCTURES IN C++" 
// BY LEENDERT AMMERDAAL, PUBLISHED BY WILEY 1996
// HERE, THE TREE IS NEVER ALLOWED TO BE EMPTY,
// SO WE DO NOT HAVE TO CHECK FOR NULL POINTERS 
  PRIVATE:
    NODE* ROOT;
    VOID LEFTROTATE(NODE* &P) {
      NODE* Q=P;
      P=P->rightNode;
      q->rightNode=p->leftNode;
      p->leftNode=q;
      q->bal-;
      if (p->bal>0) q->bal-=p->bal;
      p->bal-;
      if (q->bal<0) P->bal+=q->bal;
    }
    void RightRotate(Node* &p) {
      Node* q=p;
      p=p->leftNode;
      q->leftNode=p->rightNode;
      p->rightNode=q;
      q->bal++;
      if (p->bal<0) Q->bal-=p->bal;
      p->bal++;
      if (q->bal>0) p->bal+=q->bal;
    }
    int Insert(Node* &p,Node* q,Node* prev); 
    Node* Find(Node* p,int x) const; 
  public:
    void Clear(){root=0;}
    Node* Root(){return root;} 
    void Insert(Node* q,Node* prev) {
      Insert(root,q,prev);
    }
    Node* Find(int x) const {
      if (root) return Find(root,x);
      return root;
    }
};

CellSelection 
class CellSelection {
  private:
        
    Tree  rowTree;    // tree of sub-areas
    Row*  row;        // top most row, never deleted
    Tree  colTree;    // tree of column indices
    Col*  col;        // left most column, never deleted
    
    uint32  width;    // number of columns
    
#if EXTRA_FOR_TESTING    
    Row*  testRow;
    Col*  testCol;
#endif

    bool CreateEmpty() {
// Creates a single vixel covering the 32-bit universe      
      rowTree.Clear();
      colTree.Clear();
      try {row=new Row(kNegInfinity);}
      catch (...) {return false;}
      
      if (row->InitFailed())
        return false; 
        rowTree.Insert(row,0);
      try {col=new Col(kNegInfinity,0);}
      catch (...) {delete row; return false;}
      colTree.Insert(col,0);
      width=1;
      return true;
    }   
    
    void FreeAll() {
// Uses linked lists to delete all rows and columns    
      Row* rp=row;
      while (rp) {
        Row* nextRow=rp->Next();
        delete rp;
        rp=nextRow;
      }
      Col* cp=col;
      while (cp) {
        Col* nextCol=cp->Next();
        delete cp;
        cp=nextCol;
      }
// and clear the trees, in preparation for re-use      
      rowTree.Clear();
      colTree.Clear();
    }       
    
// The next three methods expand the vixel map by 
// insertion of new rows and columns    

    Row* SplitRow(Row* rp,int32 newTop) {
// Creates a new row as a copy of rp, and inserts
// it after it, with new coordinates marking the split    
      Row* newRow;
      try {newRow=new Row(rp);}
      catch (...) {return 0;}
      if (newRow->InitFailed())
        return 0;
      newRow->lo=newTop;
      rowTree.Insert(newRow,rp);
      return newRow;
    }
    
    bool StretchRows(uint32 index,uint32 width) {
// Allocates the next available vixel column    
      Row* rp=row;
      while (rp) {
        if (!rp->Stretch(index,width)) {
// If we run out out of memory before stretching all rows
// we fail.  Those rows that did get stretched stay there.
// No harm done.        
          return false;
        }
        rp=rp->Next();  
      }
      return true;
    }
    
    Col* SplitColumn(Col* cp,int32 newLeft) {
// Creates a new column as a copy of cp, and inserts
// it after it, with new coordinates marking the split 
      if (!StretchRows(cp->index,width))
        return 0;
      Col* newCol;
      try {newCol=new Col(newLeft,width);}
      catch (...) {return 0;}
      colTree.Insert(newCol,cp);
      width++;
      return newCol; 
    }
    
    void OutlineArea(Area a,Col** left,Row** top) const {
// locate Top-left corner closest to area.
      *top=(Row*)(rowTree.Find(a.top));
      *left=(Col*)(colTree.Find(a.left));       
    }
        
    bool DefineArea(Area a,Col** left,Row** top) {
// locate area and create new borders if needed 
      Row* rp=(Row*)(rowTree.Find(a.top));
      if (rp->lo == a.top) *top=rp; else
      if (0==(*top=SplitRow(rp,a.top))) return false;
      
      rp=(Row*)(rowTree.Find(a.bottom+1));
      if (rp->lo != a.bottom+1)
      if (!SplitRow(rp,a.bottom+1)) return false;
      
      Col* cp=(Col*)(colTree.Find(a.left));
      if (cp->lo == a.left) *left=cp; else
      if (0==(*left=SplitColumn(cp,a.left))) return false;  
      
      cp=(Col*)(colTree.Find(a.right+1));
      if (cp->lo != a.right+1)
      if (!SplitColumn(cp,a.right+1)) return false;
       
      return true; 
    } 
    
// The next set of methods scan blocks of vixels and perform
// the indicated function on each vixel    
    bool SetArea(Area a) {
      Col* left;
      Row* top;
      if (!DefineArea(a,&left,&top)) return false;
      do {
        Col* cp=left;
        do {
          top->SetVixel(cp->index);
          cp=cp->Next(); 
        } while ((cp) && (a.right>=cp->lo));
        top=top->Next();   
      } while ((top) && (a.bottom>=top->lo));
      return true;
    } 
    bool ClearArea(Area a) {

      Col* left;
      Row* top;

      if (!DefineArea(a,&left,&top)) return false;
      do {
        Col* cp=left;
        do {
          top->ClearVixel(cp->index);
          cp=cp->Next(); 
        } while ((cp) && (a.right>=cp->lo));
        top=top->Next();   
      } while ((top) && (a.bottom>=top->lo));
      return true;
    }
    bool InvertArea(Area a) {

      Col* left;
      Row* top;

      if (!DefineArea(a,&left,&top)) return false;
      do {
        Col* cp=left;
        do {
          top->InvertVixel(cp->index);
          cp=cp->Next(); 
        } while ((cp) && (a.right>=cp->lo));
        top=top->Next();   
      } while ((top) && (a.bottom>=top->lo));
      return true;
    }
    bool AllSelected(Area a,bool test) const {
      Col*  left;
      Row*   top;
      OutlineArea(a,&left,&top);

      do {
        Col* cp=left;
        do {
          if (test != IsSet(top,cp)) return false;
          cp=cp->Next(); 
        } while ((cp) && (a.right>=cp->lo));
        top=top->Next();   
      } while ((top) && (a.bottom>=top->lo));
      return true;
    }
    uint32 CountSelectedP(Area a) const {

      Col*  left;
      Row*   top;
      OutlineArea(a,&&left,&top);
      uint32 count=0;

      do {
        Col* cp=left;
        uint32 strip=0;
        do {
          if (IsSet(top,cp)) strip+=cp->Slice(a.left,a.right);
          cp=cp->Next();
        } while ((cp) && (a.right>=cp->lo));
        count+=strip*top->Slice(a.top,a.bottom);
        top=top->Next();        
      } while ((top) && (a.bottom>=top->lo));
      return count;
    }
   
    bool IsSet(Row* rp,Col* cp) const{
// Tests if a vixel is set, i.e. if the cells represented
// by the sub-area defined by 1 row and 1 column, are
// in the CellSelection.
      return rp->Vixel(cp->index);
    }
    
  public:
    CellSelection(void) {

      /* create an empty selection */

      CreateEmpty();
#if EXTRA_FOR_TESTING    
      testRow=0;
      testCol=0;
#endif      
    }  
    ~CellSelection(void) {

      /* free any allocated memory */

      FreeAll();
    }  
    bool Clear() {

      /* make the selection empty */

      FreeAll();
      return CreateEmpty();
    }  
    bool Add(Area area) {

      /* add the area of cells to this selection */

      if (!area.IsEmpty()) return SetArea(area);
      return true;
    }  
    bool Remove(Area area) {

      /* remove the area of cells from this selection */      

      if (!area.IsEmpty()) return ClearArea(area);
      return true;
    }  
    bool Invert(Area area) {

      /* remove cells in the area that are also in this selection
        and add the area cells that are not in this selection */

      if (!area.IsEmpty()) return InvertArea(area);
      return true;
    }  
    bool Add(const CellSelection & otherSelection) {

      /* add the otherSelection to this selection */

      Row* rp=otherSelection.row;
      do {
        Area a;
        a.top=rp->lo;a.bottom=rp->Limit();
        Col* cp=otherSelection.col;
        do {
          if (IsSet(rp,cp)) {
            a.left=cp->lo;a.right=cp->Limit();
            if (!SetArea(a)) return false;
          }  
          cp=cp->Next();
        } while (cp);
        rp=rp->Next();
      } while (rp);
      return true;

    } 
    bool Remove(const CellSelection & otherSelection) {

      /* remove the otherSelection from this selection */

      Row* rp=otherSelection.row;
      do {
        Area a;
        a.top=rp->lo;a.bottom=rp->Limit();
        Col* cp=otherSelection.col;
        do {
          if (IsSet(rp,cp)) {
            a.left=cp->lo;a.right=cp->Limit();
            if (!ClearArea(a)) return false;
          }  
          cp=cp->Next();
        } while (cp);
        rp=rp->Next();
      } while (rp);
      return true;
    }  
    bool Invert(const CellSelection & otherSelection) {

      /* remove cells in the otherSelection that are also in this selection
          and add the otherSelection cells that are not in this selection */

      Row* rp=otherSelection.row;
      do {
        Area a;
        a.top=rp->lo;a.bottom=rp->Limit();
        Col* cp=otherSelection.col;
        do {
          if (IsSet(rp,cp)) {
            a.left=cp->lo;a.right=cp->Limit();
            if (!InvertArea(a)) return false;
          }  
          cp=cp->Next();
        } while (cp);
        rp=rp->Next();
      } while (rp);
      return true;
    }  
    bool AllSelected(Area area) {

      /* return TRUE if all cells in the area are selected */

      if (area.IsEmpty()) return false;
      return AllSelected(area,true);
    }  
    uint32 CountSelected(Area area) {

      /* count cells that are "on" */

      if (area.IsEmpty()) return 0;
      return CountSelectedP(area);
    }  
    bool EqualSelected(const CellSelection & otherSelection) {

      /* return TRUE if otherSelection equals this selection */

      Row*  rp=row;
      do {
        Area a;
        a.top=rp->lo;a.bottom=rp->Limit();
        Col* cp=col;
        do {
          a.left=cp->lo;a.right=cp->Limit();
          if (!otherSelection.AllSelected(a,IsSet(rp,cp)))
              return false;
          cp=cp->Next();
        } while (cp);
        rp=rp->Next();
      } while (rp);
      return true;
    }  

#if EXTRA_FOR_TESTING
    const int Width() const {return width;}
    const int Height() const {
      int h=0;
      Row* rp=row;
      while (rp) {h++;rp=rp->Next();}
      return h;
    }
    void ResetTestAreas() {
      testRow=row;
      testCol=col;
    }
    bool NextTestArea(Area* a) {
      while (testRow) {
        Row* rp=testRow;
        while (testCol) {
          Col* cp=testCol;
          testCol=cp->Next();
          if (IsSet(rp,cp)) {
            a->left=cp->lo;
            a->top=rp->lo;
            a->right=cp->Limit();
            a->bottom=rp->Limit();
            return true;
          }
        }
        testRow=rp->Next();
        testCol=col;
      }
      return false;
    }
#endif    
};

#ifndef CELLS_DEFINITIONS_INCLUDED
#define CELLS_DEFINITIONS_INCLUDED

// We avoid Inlining of recursive methods
    int Tree::Insert(Node* &p,Node* q,Node* prev) {

// insert node q in (sub-)tree rooted in p    
      int deltaH=0;
      if (p==0) {
        p=q;
        deltaH=1;

// also insert q in linear list, following prev        
        if (prev) {
          p->nextNode=prev->nextNode;
          prev->nextNode=p;
        }  
      } else if (q->lo > p->lo) {
        if (Insert(p->rightNode,q,prev)) {
          p->bal++;
          if (p->bal==1) deltaH=1;
          else if (p->bal==2) {
            if (p->rightNode->bal==-1)
              RightRotate(p->rightNode);
            LeftRotate(p);  
          }
        }
      } else if (q->lo < P->lo) {
        if (Insert(p->leftNode,q,prev)) {
          p->bal-;
          if (p->bal==-1) deltaH=1;
          else if (p->bal==-2) {
            if (p->leftNode->bal==1)
              LeftRotate(p->leftNode);
            RightRotate(p);  
          }
        }      
      }
      return deltaH;
    }
    Node* Tree::Find(Node* p,int x) const {
// find nearest p->lo <= X  
// NEVER RETURNS A NULL POINTER
      IF (P->lo<X) {
        IF (P->rightNode) {
          Node* q=Find(p->rightNode,x);
          if (q->lo<=X) RETURN Q;
        }  
      }  
      IF (P->lo>x) {
        if (p->leftNode) return Find(p->leftNode,x);
      } 
      return p;
    }
#endif
 
AAPL
$101.79
Apple Inc.
+0.21
MSFT
$46.68
Microsoft Corpora
+0.16
GOOG
$589.27
Google Inc.
+4.50

MacTech Search:
Community Search:

Software Updates via MacUpdate

iMazing 1.0 - Complete iOS device manage...
iMazing (formerly DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and... Read more
Xcode 6.0.1 - Integrated development env...
Apple Xcode is Apple Computer's integrated development environment (IDE) for OS X. The full Xcode package is free to ADC members and includes all the tools you need to create, debug, and optimize... Read more
Apple Safari 7.1 - Apple's Web brow...
Apple Safari in OS X Mavericks brings you all-new ways to find and enjoy the best of the web. It works with iCloud to give you a seamless browsing experience across all your devices. It looks out for... Read more
Delivery Status 6.1.2 - Check delivery s...
Delivery Status displays delivery status of packages for a variety of shipment services. Can't wait for your packages to arrive? Don't waste your time checking the site constantly, just open this all... Read more
Mavericks Cache Cleaner 8.0.9 - Clear ca...
Mavericks Cache Cleaner is an award-winning general purpose tool for OS X. MCC makes system maintenance simple with an easy point-and-click interface to many OS X functions. Novice and expert users... Read more
OneNote 15.2.2 - Free digital notebook f...
OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that's too important to forget. Whether you're at... Read more
Apple Configurator 1.6 - Configure and d...
Apple Configurator makes it easy for anyone to mass configure and deploy iPhone, iPad, and iPod touch in a school, business, or institution. Three simple workflows let you prepare new iOS devices... Read more
SpamSieve 2.9.16 - Robust spam filter fo...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
OS X Server 3.2.1 - For OS X 10.9.5 Mave...
OS X Server is the next generation of Apple's award winning server software. Designed for OS X and iOS devices, OS X Server makes it easy to share files, schedule meetings, synchronize contacts, host... Read more
Apple Security Update 2014-004 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more

Latest Forum Discussions

See All

Down Among the Dead Men (Games)
Down Among the Dead Men 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Avast! Take to the high seas in a fully interactive piratical tale of broadsides and buccaneers. From author Dave... | Read more »
Sling Adds Chromecast Support Through Sl...
Sling Adds Chromecast Support Through Slingplaye​r Mobile Apps Posted by Jessica Fisher on September 18th, 2014 [ permalink ] | Read more »
How to Completely Delete Your iPhone’s C...
The iPhone 6 is out tomorrow, and plenty of people are excited about it. So much so that they’re planning to – or already have – traded in their old iPhone to go towards it. The thing about trading in hardware is it’s very important to make sure... | Read more »
Dragon Quest I Review
Dragon Quest I Review By Andrew Fisher on September 18th, 2014 Our Rating: :: THINE QUEST AWAITETHUniversal App - Designed for iPhone and iPad Its historical significance aside, Dragon Quest 1 is a fun, campy, difficult, thoroughly... | Read more »
It Came From Canada: Overkill 3
Overkill 3 is like every trope of big modern gaming rolled into one. It’s a sequel to an action-packed military shooter. It’s flashy and scripted and flaunts its sophisticated graphics. And it’s a mobile game with a heavy emphasis on in-app... | Read more »
New Modes and Leader Boards in Update fo...
New Modes and Leader Boards in Update for Rules! Posted by Jessica Fisher on September 18th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
TwistedRun Review
TwistedRun Review By Rob Thomas on September 18th, 2014 Our Rating: :: DON'T TWIST YOUR ANKLE!Universal App - Designed for iPhone and iPad TwistedRun is kind of like running up a giant curly fry into the sky. Or maybe that was just... | Read more »
Scope Review
Scope Review By Jennifer Allen on September 18th, 2014 Our Rating: :: LOCATION AWAREiPhone App - Designed for the iPhone, compatible with the iPad Want to easily find photos from around the world based on their location? Scope is a... | Read more »
HipstaFox Review
HipstaFox Review By Jordan Minor on September 18th, 2014 Our Rating: :: FANTASTIC MR. FOXUniversal App - Designed for iPhone and iPad HipstaFox is a great single that makes players long for the whole album.   | Read more »
Ninja Raft (Games)
Ninja Raft 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: ** Special Launch Price ** "Ninja Raft is definitely the game to play if you’re into Tower Defense games and want to play something... | Read more »

Price Scanner via MacPrices.net

Save up to $300 on the price of a new Mac wit...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
13-inch 2.8GHz Retina MacBook Pro available f...
B&H Photo has the new 2014 13″ 2.8GHz Retina MacBook Pro on sale for $1699.99 including free shipping plus NY sales tax only. They’ll also include free copies of Parallels Desktop and LoJack for... Read more
16GB iPad Air on sale for $449, save $50
Walmart has the 16GB iPad Air WiFi on sale for $449 on their online store for a limited time. Choose free home shipping or free local store pickup. Their price represents a $50 savings over standard... Read more
13-inch 256GB MacBook Air on sale for $1099,...
B&H Photo has the 2014 13″ 1.4GHz 256GB MacBook Air on sale for $1099.99. Shipping is free, and B&H charges NY sales tax only. Their price is $100 off MSRP. Read more
Toshiba Introduces TransMemory ID High-Speed...
Toshiba’s Digital Products Division (DPD), a division of Toshiba America Information Systems, Inc., today introduced the TransMemory ID USB 3.0 Flash Drive, a simpler storage solution for people who... Read more
New iPads and OS X Yosemite Release Coming Oc...
The DailyDot’s Micah Singleton reports that Apple is planning to hold its next product announcement event on Oct. 21, at which it will unveil the iPad Air 2 and iPad mini 3 and release a final build... Read more
Logitech Bluetooth Multi-Device Cross-Platfor...
Logitech has an enviable track record of making some of the best computer keyboards and mice. At least in my estimation, the best freestanding keyboards I’ve ever used have been Logitech units,... Read more
Roundup of Apple refurbished iPad Airs and iP...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Sprint offers 16GB iPad mini for $199.99 with...
Sprint is offering 1st generation 16GB iPad minis for $199.99 with a 2-year service agreement. Standard MSRP for this iPad is $429. Their price is the lowest available for this model. Read more
2.5GHz Mac mini remains on sale for $549, sav...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more

Jobs Board

Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.