Jun 97 Challenge

Volume Number: 13 (1997)
Issue Number: 6
Column Tag: Programmer's Challenge

# June 1997 Programmer's Challenge

by Bob Boonstra, Westford, MA

## Turing Machine

A Turing Machine is a finite state machine augmented with an infinite amount of external storage, formatted as a sequence of squares on a linear tape. The behavior of the Turing Machine is described by a set of rules, each of which contains a current state, an input symbol, a next state, an output symbol, and a move direction. At any given time, the Turing Machine is described by the current internal state, the position of its read-write head on the tape, and the contents of the tape. Each clock cycle the Turing Machine reads the square of the input tape on which the read-write head is positioned, replaces the contents of that square by writing an output symbol based on the input and the current state, and moves left or right one square on the tape (or halts). Because they have access to an unbounded amount of storage, Turing Machines can solve problems that finite state machines cannot. An example of such a problem is parenthesis checking. Given an input of left and right parentheses, delimited by the special symbol 'A', such as:

`0000A(()((())(((A0000`

...the following set of rules will determine whether the parentheses are will-formed, meaning that they can be paired off so that each left parenthesis has a balancing right parenthesis:

 State Input NewState Output Move 0 ) 1 X Left 0 ( 0 ( Right 0 A 2 A Left 0 X 0 X Right 1 ) 1 ) Left 1 ( 0 X Right 1 A 1 0 Halt 1 X 1 X Left 2 ( 2 0 Halt 2 A 2 1 Halt 2 X 2 X Left

This machine scans right in state 0 looking for a right parenthesis. When it finds one, it moves to state one, replaces the right parenthesis with an 'X', and moves to state 1 to scan for a left parenthesis., which it also replaces with an 'X'. If it encounters the 'A' delimiter when looking for a balancing parenthesis, it halts after writing a '0', indicating that the parentheses are not well-formed. If all parentheses are paired off, it writes a '1' indicating the input is well-formed.

Your Challenge this month is to implement a Turing Machine. The prototype for the code you should write is:

```typedef unsigned long ulong;

typedef enum {kMoveLeft=-1,kHalt=0, kMoveRight=1} MoveDir;

typedef struct TMRule { /* rule in program for TM */
ulong oldState;      /* this rule fires when currentState == oldState and */
ulong inputSymbol;   /*  currentSymbol == inputSymbol */
ulong newState;      /* set currentState to newState when this rule fires */
ulong outputSymbol;  /* write outputSymbol to tape when this rule fires */
MoveDir moveDirection; /* move left or right as indicated when this rule fires */
} TMRule;

typedef void (*TMMoveProc) (
ulong outputSymbol,
ulong newState,
MoveDir moveDirection
);

Boolean /* success */ TuringMachine(
const TMRule theRules[],  /* pointer to program for TM */
ulong numRules,           /* number of rules in TM program */
ulong *theTape,           /* pointer to input tape for TM */
ulong tapeLen,            /* theTape[0]..theTape[tapeLen-1] is valid */
TMMoveProc ReportMove     /* callback proc to inform caller of each move */
);
```

When your TuringMachine encounters a rule with a moveDirection of kHalt, you should make a final callback to ReportMove and then return TRUE. If your TuringMachine exceeds the tapeLen of theTape, or if you are unable to find a rule that applies to your current machine state and the input symbol, you should return FALSE. It is my intent to provide all necessary input rules and a sufficient length of tape, but your machine should fail gracefully if an input bug or an implementation bug results in running out of tape or encountering a bad input symbol.

Your code will be timed with a sequence of rule/tape pairs, and the solution that completes execution of the inputs correctly in the shortest total time will be the winner. Half of the tests will use a "universal" Turing Machine, where the rules describe a general Turing Machine interpreter, and the input tape contains another Turing Machine program. The time executed by the ReportMove callback will be included in your solution time. The callback will look something like the following.

```static void ReportMove(long outputSymbol, long newState, MoveDir moveDirection)
{
if ((gTapePos>=0) && (gTapePos<gTapeLen))
gTape[gTapePos] = outputSymbol;
gTapePos += moveDirection;
gState = newState;
}
```

You may not modify the input rules pointed to by theRules, but you may allocate reasonable additional storage if you would like to preprocess the rules in some way, provided you deallocate the storage before returning.

For those of you that would like additional information on Turing Machines, you can refer to almost any textbook on automata theory or the theory of computation. My personal favorite is Computation, Finite and Infinite Machines, by Marvin Minsky, © 1976 by Prentice-Hall.

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 to Gregory Cooper for narrowly defeating the second place entry by Jeff Mallett in the March Hex Challenge. Hex is played on an NxN rhombus of hexagons, with players alternately occupying hexagons, one playing vertically and the other horizontally, each trying to complete an unbroken chain before the other does. The Challenge awarded 10 points for each victory in a round-robin tournament, with the score reduced based on the execution time of the winning solution.

The third-place solution by Eric Hangstefer used a purely offensive strategy, building bridges in an attempt to force the opponent to play defense. The other two solutions applied both offensive and defensive techniques, and between them won all of the games in the tournament. Gregory's solution plays defense whenever it believes that its opponent is closer to a solution than he is. To accomplish this, he maintains a Path data structure for himself and for his opponent identifying what he believes to be the best (shortest) path across the board for each player. A path score is maintained by counting the number of hexagons along the path that still need to be occupied to complete an unbroken chain (excluding "two-bridge" positions where a connection is guaranteed). One key to understanding the winning solution is the ExtendPathToEdge routine, used by the BestPathAcrossBoard routine to find a short route to each edge from a central hexagon.

The tournament consisted of three test cases, with hex boards of size 8, 10, and 18, with each solution competing against each other twice, once playing first and once playing second. Gregory's solution and Jeff's solution competed against one another six times, and, interestingly enough, in all but one of those contests, the solution playing second (i.e., horizontal) won the game. In most of the games, Gregory's and Jeff's solutions required comparable execution time, except in two instances where Gregory's solution took very long to make its final move. This behavior accounted for the fact that the two solutions were very close in cumulative points, even though Gregory won two more games. By virtue of having the highest point total, the most victories, and (as a tie-breaker) the smallest code, Gregory's solution is the winner.

The final position in the 10x10 game where Gregory played the vertical orientation and won is reproduced below for your enjoyment. Note the vertical player's focus on a single path by comparison with the more scattered hexagons occupied by the horizontal player.

``` 0 1 2 3 4 5 6 7 8 9
0 - - V H H - - - - H
1 - - V V - H - - H V
2 - - H V - - H - V -
3 - - V H H H - - - -
4 - - V - - V - V - -
5 - V H H - - - - - -
6 - V V H H - V - - -
7 - - V V H - - V - -
8 - - H V - H - - - -
9 - - V H - - - - - -
```

The table below lists for each entry the number of tournament wins, the total tournament points earned, and the code and data sizes. 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.

 Name Wins Points Code Data Gregory Cooper (34) 10 80.08 8028 628 Jeff Mallett (64) 8 79.98 8608 392 Eric Hangstefer (2) 0 0.00 5236 88

## Top 20 Contestants

Here are the Top Contestants for the Programmer's Challenge. The numbers below include points awarded over the 24 most recent contests, including points earned by this month's entrants.

 Rank Name Points Rank Name Points 1. Munter, Ernst 184 11. Cutts, Kevin 21 2. Gregg, Xan 114 12. Nicolle, Ludovic 21 3. Larsson, Gustav 67 13. Picao, Miguel Cruz 21 4. Cooper, Greg 54 14. Brown, Jorg 20 5. Lengyel, Eric 40 15. Gundrum, Eric 20 6. Boring, Randy 37 16. Higgins, Charles 20 7. Mallett, Jeff 37 17. Kasparian, Raffi 20 8. Lewis, Peter 32 18. Slezak, Ken 20 9. Antoniewicz, Andy 24 19. Studer, Thomas 20 10. Beith, Gary 24 20. Karsh, Bill 19

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 Gregory's winning solution:

```Hex_Strategy.c ® 1997 Gregory Cooper

// *****************************************************************
// General idea: My strategy tries to find the quickest routes across the
// board, both for itself and for its opponent. If the opponent has a better,
// shorter route than my strategy does, then my strategy makes a defensive move
// (one that makes it more difficult for the opponent to complete his route).
// Otherwise, it makes an offensive move (one which brings its own route closer
// to completion). It re-traces the routes during each turn, looking for
// necessary modifications and scoring changes.
// *****************************************************************

#include "Storage.h"

// an enumeration for move types
typedef enum
{
// counter-clockwise from right
right,                       // 0
upRightTwoBridge,            // 30
upRight,                     // 60
upTwoBridge,                 // 90
upLeft,                      // 120
upLeftTwoBridge,             // 150
left,                        // 180
downLeftTwoBridge,           // 210
downLeft,                    // 240
downTwoBridge,               // 270
downRight,                   // 300
downRightTwoBridge,          // 330
noDirection                    // undefined
} Direction;

// a data structure for representing potential routes to edges or to other chips
typedef struct Path
{
long        row;             // row of piece on board
long        col;             // column of piece on board
Direction   nextDirection;   // direction to next piece
Direction   prevDirection;   // direction to prev piece
Boolean     occupied;        // location actually taken?
Boolean     center;          // origin of path?
struct Path *next;           // next piece in path
struct Path *prev;           // previous piece in path
} Path;

// a data type for the playing chips
typedef enum {
empty,
blue,   // plays first
red      // plays second
} Chip;

// an enumeration for disposing of unneeded paths
// (used by the BetterPath function and its clients)
typedef enum {
leaveBad,   // indicates that inferior strategy should be left alone
forgetBad   // indicates that inferior strategy should be disposed
} PathAction;
// an enumeration for the edges
typedef enum {
leftEdge,
rightEdge,
topEdge,
bottomEdge
} Edge;

// an enumeration for path disruptions
typedef enum {
noDisruption,       // move did not block path
inTwoBridge,        // move occupied part of a two-bridge
inSpot              // move occupied a strategic location
} Disruption;

Function Prototypes
Path *BestPathAcrossBoard(long boardSize, Chip *theBoard,
long startRow, long startCol, Chip color);
// tries to find a path across the board through (startRow, startCol)
// PRECONDITIONS: boardSize is the number of rows or columns
// on the board; theBoard stores information about the board;
// (startRow, startCol) indicates a piece of the given color on the board;
// color indicates which player for whom the path is to be found
// POSTCONDITIONS: returns a pointer to the path found, beginning with
// (startRow, startCol), or returns nil if no path exists

Boolean ExtendPathToEdge(long boardSize, Chip *theBoard,
Path *path, Edge edge);
// tries to find a path from path to the given edge
// PRECONDITIONS: path is an incomplete path, edge is one of the four edges,
// boardSize is the number of rows or columns on the board, theBoard defines
// the playing board
// POSTCONDITIONS: if a path from the edge exists, it is found and the value
// true is returned; otherwise, all memory associated with the path is freed
// and it returns false

void PrioritizeMoves(Edge edge, Direction moveList[12]);
// determines the order in which potential moves in a path should be attempted
// PRECONDITIONS: edge is the edge to which we are trying to move
// POSTCONDITIONS: moveList contains the moves in order from most to
// least direct

Boolean PossibleMove(long boardSize, Chip *theBoard,
long row, long col, Path *path, Direction move,
Chip color);
// determines whether placing a piece in a given location is feasible
// PRECONDITIONS: boardSize is the number of rows or columns on the board;
// theBoard defines the board; (row, col) is the piece from which we are
// moving; move is the direction in which we are moving; color is the color of
// the player
// POSTCONDITIONS: returns true if the given move is possible, false otherwise

void FindNewLocation(long row, long col, Direction move,
long *newRow, long *newCol);
// determines the location of a piece adjacent to another piece in a given
// direction
// PRECONDITIONS: (row, col) indicates the initial piece, move is the direction
// of the move
// POSTCONDITIONS: (*newRow, *newCol) contain the location of the new piece

Direction OppositeDirection(Direction move);
// determines the direction opposite a given direction
// PRECONDITIONS: move is a direction
// POSTCONDITIONS: returns the direction opposite move

Boolean OnBoard(long boardSize, long row, long col);
// determines whether a given piece lies on the board
// PRECONDITIONS: boardSize is the size of the board,
// (row, col) is the location of the desired piece
// POSTCONDITIONS: returns whether the piece is
// within the boundaries of the board

Boolean IsTwoBridge(Direction move);
// determines whether a connection in a given direction is a two-bridge
// PRECONDITIONS: move is the direction of the desired connection
// POSTCONDITIONS: returns true if the connection is a two-bridge;
// otherwise returns false

Boolean TwoBridgeFree(long boardSize, Chip *theBoard,
long row, long col, Direction move);
// determines whether a given two-bridge is free
// PRECONDITIONS: (row, col) contains one of the pieces in in the two-bridge,
// move is the direction of the bridge, boardSize and theBoard define the board
// POSTCONDITIONS: returns true if the spaces in between are free;
// otherwise, returns false

Boolean PieceOnEdge(long row, long col, long boardSize,
Edge edge);
// determines whether a given piece is on a desired edge
// PRECONDITIONS: (row, col) indicate a piece, boardSize is the number of rows
// or columns on the board, edge is the desired edge
// POSTCONDITIONS: returns true if the piece is on the edge;
// otherwise returns false

void FreePath(Path *path);
// disposes the memory associated with a path
// PRECONDITIONS: path points to a path
// POSTCONDITIONS: the memory associated with the path is freed.

Boolean ValidMove(long boardSize, Chip *theBoard,
long row, long col);
// determines whether a desired move is legal
// PRECONDITIONS: boardSize contains the number of rows or columns on the
// board; theBoard defines the playing board; (row, col) is the location of the
// intended move
// POSTCONDITIONS: returns true if the piece is on the board and not already
// taken; otherwise false

Disruption MoveInPath(Path *path, long row, long col);
// determines whether a desired move is in a path
// PRECONDITIONS: path describes a path across the board;
// (row, col) defines the intended move
// POSTCONDITIONS: returns noDisruption if the move is not in the path,
// inTwoBridge if it threatens an established two-bridge, or inSpot if it
// occupies a location in the path (including a two-bridge whose end-points
// have not been secured)

Boolean TwoBridgeThreatened(long row, long col,
long threatRow, long threatCol, Direction move);
// determines whether a two-bridge is threatened by a given move
// PRECONDITIONS: (row, col) is the origin of a two-bridge; (threatRow,
// threatCol) is the new move; move is the direction of the two-bridge
// POSTCONDITIONS: returns true if the two-bridge is threatened by the move

void UpdatePath(Path *path, long row, long col);
// PRECONDITIONS: path points to a path across the board;
// (row, col) is the location of the move
// POSTCONDITIONS: the location in the path is marked as being occupied;
// sometimes, as when a two-bridge is filled in (and destroyed), an extra node
// is added to the path list

Direction GetDirection(long row1, long col1, long row2,
long col2);
// determines the direction from one piece to another
// PRECONDITIONS: (row1, col1) and (row2, col2) define two pieces
// POSTCONDITIONS: the direction from (row1, col1) to (row2, col2) is returned

Path *BetterPath(Path *path1, Path *path2,
PathAction action);
// determines which of two paths is superior to the other
// PRECONDITIONS: path1 and path2 point to paths
// POSTCONDITIONS: the better of the two paths is returned;
// if action is forgetBad, then the inferior path is disposed

long PathRating(Path *path);
// rates a path
// PRECONDITIONS: path is a path
// POSTCONDITIONS: a rating for the path is returned
// (always positive, low numbers are better)

void FillThreatenedTwoBridge(Path *path, long threatRow,
long threatCol, long *row, long *col);
// determines where to move in order to secure a threatened two-bridge
// PRECONDITIONS: path points to a path;
// (threatRow, threatCol) is the move which threatened the two-bridge
// POSTCONDITIONS: (row, col) is the move needed to secure
// the free half of the two-bridge

Path *TakeDetour(long boardSize, Chip *theBoard, Path *path,
long row, long col, Chip color);
// finds a new path after it has been disrupted
// PRECONDITIONS: path points to a path; (row, col)
// indicates a move which disrupted the path
// POSTCONDITIONS: the path is corrected, if possible, so that it avoids the
// opponent's piece, and it is then returned; nil is returned if no new path
// can be found

void FindBestMove(Path *ourPath, Path *oppPath, long *row,
long *col);
// TRIES to determine the best move
// PRECONDITIONS: ourPath and oppPath are the expected
// paths of the player and the opponent, respectively
// POSTCONDITIONS: (*row, *col) indicate the chosen move, which should be
// decent; if the opponent's path is better, it should be a defensive move; if
// not, it should be an offensive move; whenever possible, offensive and
// defensive moves are
// made to coincide with one another

Boolean NextToEdge(long row, long col, long boardSize,
Edge edge);
// determines if a piece is next to a given edge
// PRECONDITIONS: (row, col) is a piece; boardSize is the size of the board,
// edge is the edge we want to be near
// POSTCONDITIONS: returns true if the piece if one hex from the edge

Boolean Hex(long boardSize, long oppRow, long oppCol,
long *moveRow, long *moveCol, void *privStorage,
Boolean newGame, Boolean playFirst);

Hex
Boolean Hex(long boardSize, long oppRow, long oppCol,
long *moveRow, long *moveCol, void *privStorage,
Boolean newGame, Boolean playFirst)
{
// board storage (preserved between turns)
static Chip   *theBoard;
// expected paths (also preserved between turns)
static Path *ourPath, *oppPath;
// a temporary path used for comparisons
Path *newPath;
Disruption disruption; // holds path disruptions

if (newGame)
{
long i;

// initialize the private storage allocation system
InitializeHeap(privStorage, 0x100000); // 1 MB
// initialize storage space for the board
theBoard = AllocateBlock(boardSize * boardSize);
for (i = 0; i < boardSize * boardSize; i++)
theBoard[i] = empty;
// indicate that no paths have yet been determined
ourPath = oppPath = nil;
if (playFirst)
{
// go in the middle
*moveRow = (boardSize - 1) / 2;
*moveCol = boardSize / 2;
// mark the chip on the board
theBoard[*moveRow * boardSize + *moveCol] =
blue; // blue because we are moving first
// try to determine the shortest route across the board through
// the spot where we just moved
ourPath = BestPathAcrossBoard(boardSize,
theBoard, *moveRow, *moveCol, blue);
return true;
} // end if
} // end if
// check the opponent's move
if (!ValidMove(boardSize, theBoard, oppRow, oppCol))
// if it is illegal, abort here
return false;
// mark the opponent's move on the board
theBoard[oppRow * boardSize + oppCol] =
playFirst ? red : blue;
// if the opponent's move was in his path (offensive)
if (MoveInPath(oppPath, oppRow, oppCol))
// update his path
UpdatePath(oppPath, oppRow, oppCol);
else // opponent did not continue his expected path
{
// try to find a probable route for the opponent through the piece
// where he just moved
newPath = BestPathAcrossBoard(boardSize, theBoard,
oppRow, oppCol, playFirst ? red : blue);
// if his new route is better than his old one, use it instead
} // end else
// determine whether his move blocked or otherwise disrupted our path
disruption = MoveInPath(ourPath, oppRow, oppCol);
if (disruption == inTwoBridge)
{
// move into the other half of the
// two-bridge automatically
FillThreatenedTwoBridge(ourPath, oppRow, oppCol,
moveRow, moveCol);
// mark the move on the board
theBoard[*moveRow * boardSize + *moveCol] =
playFirst ? blue : red;
// update the path
UpdatePath(ourPath, *moveRow, *moveCol);
} // end if
else // no automatic response
{
if (disruption == inSpot)
// try to find a new path from just
// before the disruption (the unaffected
// part of the path can remain)
ourPath = TakeDetour(boardSize, theBoard,
ourPath, oppRow, oppCol, playFirst ? blue :
red);
// try to determine the best move and then make it
FindBestMove(ourPath, oppPath, moveRow, moveCol);
// if the move was invalid (happens when neither
// player has a path), just try to find a valid move
if (!ValidMove(boardSize, theBoard, *moveRow,
*moveCol))
{
Boolean moveFound = false;
for (*moveRow = 0; !moveFound && *moveRow
< boardSize; (*moveRow)++)
{
for (*moveCol = 0; !moveFound && *moveCol
< boardSize; (*moveCol)++)
{
if (ValidMove(boardSize, theBoard,
*moveRow, *moveCol))
{
moveFound = true;
(*moveRow)--;
(*moveCol)--;
} // end if
} // end for
} // end for
} // end if
// mark the move on the board
theBoard[*moveRow * boardSize + *moveCol] =
playFirst ? blue : red;
// check to see if the move was in our path
if (MoveInPath(ourPath, *moveRow, *moveCol))
// if so, update it
UpdatePath(ourPath, *moveRow, *moveCol);
else
{
// otherwise, try to find a path through the
// new location
newPath = BestPathAcrossBoard(boardSize,
theBoard, *moveRow, *moveCol,
playFirst ? blue : red);

// if the new path is better than the old one, use it instead
ourPath = BetterPath(ourPath, newPath,
} // end else
} // end if
// if our move blocked the opponent's path,
// try to find him a new path from just before the disruption
if (MoveInPath(oppPath, *moveRow, *moveCol))
oppPath = TakeDetour(boardSize, theBoard, oppPath,
*moveRow, *moveCol, playFirst ? red : blue);
return true;
} // end Hex

BestPathAcrossBoard
Path *BestPathAcrossBoard(long boardSize, Chip *theBoard,
long startRow, long startCol, Chip color)
{
// initial path is just the starting hex
Path *thePath = AllocateBlock(sizeof (Path));

thePath->row = startRow;
thePath->col = startCol;
thePath->occupied =    // should be true always
theBoard[startRow * boardSize + startCol] == color;
// no connections yet
thePath->prev = thePath->next = nil;
thePath->prevDirection = thePath->nextDirection =
noDirection;
thePath->center = true;
// find the best path from (startRow, startCol) to the
// top (if blue) or left (if red) edge
if (!ExtendPathToEdge(boardSize, theBoard, thePath,
color == blue ? topEdge : leftEdge))
{
FreePath(thePath);
return nil;
} // end if
// find the best path from (startRow, startCol) to the
// other friendly edge
if (!ExtendPathToEdge(boardSize, theBoard, thePath,
color == blue ? bottomEdge : rightEdge))
{
FreePath(thePath);
return nil;
} // end if
// if we made it here, we succeeded
return thePath;
} // end BestPathAcrossBoard

ExtendPathToEdge
Boolean ExtendPathToEdge(long boardSize, Chip *theBoard,
Path *path, Edge edge)
{
Direction moveList[12]; // stores the move priorities
// which color we are
Chip color = edge == leftEdge || edge == rightEdge ?
red : blue;
long moveNum; // an index for when we try to move
// which way the path is going
Boolean goingForward = edge == rightEdge ||
edge == bottomEdge;
Boolean result; // did we succeed yet

// prioritize the moves according to which edge we
// are seeking and the current location in the path
PrioritizeMoves(edge, moveList);
// stop if we are already at an edge
if (PieceOnEdge(path->row, path->col, boardSize, edge))
return true;
// see if we are next to the edge
if (NextToEdge(path->row, path->col, boardSize, edge))
{
Direction d;
long newRow, newCol;

// make the simplest move to reach the edge
for (d = right; d < noDirection; d++)
if (!IsTwoBridge(d))
{
FindNewLocation(path->row, path->col, d,
&newRow, &newCol);
if (PieceOnEdge(newRow, newCol, boardSize,
edge) && ValidMove(boardSize, theBoard,
newRow, newCol))
{
// allocate space for the new node
Path *newNode =
AllocateBlock(sizeof (Path));
newNode->row = newRow;
newNode->col = newCol;
// determine if it has been secured or not
newNode->occupied = theBoard[
newNode->row * boardSize +
newNode->col] == color;
// it is not the center (it is an extension)
newNode->center = false;
// link the new node to the old path
if (goingForward)
{
path->nextDirection = d;
path->next = newNode;
newNode->prevDirection =
OppositeDirection(d);
newNode->prev = path;
newNode->next = nil;
newNode->nextDirection =
noDirection;
} // end if
else
{
path->prevDirection = d;
path->prev = newNode;
newNode->nextDirection =
OppositeDirection(d);
newNode->next = path;
newNode->prev = nil;
newNode->prevDirection =
noDirection;
} // end else
return true;
} // end if
} // end for
} // end if
// first look to connect with a piece that is already on the board
for (result = false, moveNum = 0;
!result && moveNum < 9; moveNum++)
{
// once a single move works, try to extend from
// the new location to the same edge
if (PossibleMove(boardSize, theBoard, path->row,
path->col, path, moveList[moveNum], color))
{
// allocate space for the new node
Path *newNode = AllocateBlock(sizeof (Path));

// abort if there is not enough memory
if (!newNode)
return false;
// define its position
FindNewLocation(path->row, path->col,
moveList[moveNum], &newNode->row,
&newNode->col);
// determine if it has been secured or not
newNode->occupied = theBoard[newNode->row *
boardSize + newNode->col] == color;
// only make the move if there is already a connection
if (!newNode->occupied)
{
FreeBlock(newNode);
continue;
}
// it is not the center (it is an extension)
newNode->center = false;
// link the new node to the old path
if (goingForward)
{
path->nextDirection = moveList[moveNum];
path->next = newNode;
newNode->prevDirection =
OppositeDirection(moveList[moveNum]);
newNode->prev = path;
newNode->next = nil;
newNode->nextDirection = noDirection;
} // end if
else
{
path->prevDirection = moveList[moveNum];
path->prev = newNode;
newNode->nextDirection =
OppositeDirection(moveList[moveNum]);
newNode->next = path;
newNode->prev = nil;
newNode->prevDirection = noDirection;
} // end else
// see if we can get to an edge
if (ExtendPathToEdge(boardSize, theBoard,
newNode, edge))
{
result = true;
} // end if
else
{
FreeBlock(newNode);
if (goingForward)
{
path->next = nil;
path->nextDirection = noDirection;
} // end if
else
{
path->prev = nil;
path->prevDirection = noDirection;
} // end else
} // end else
} // end if
} // end for
// try moves until we run out or one works
for (moveNum = 0; !result && moveNum < 7; moveNum++)
{
// once a single move works, try to extend from
// the new location to the same edge
if (PossibleMove(boardSize, theBoard, path->row,
path->col, path, moveList[moveNum], color))
{
// allocate space for the new node
Path *newNode = AllocateBlock(sizeof (Path));

// abort if there is not enough memory
if (!newNode)
return false;
// define its position
FindNewLocation(path->row, path->col,
moveList[moveNum], &newNode->row,
&newNode->col);
// determine if it has been secured or not
newNode-occupied = theBoard[newNode-row *
boardSize + newNode-col] == color;
// it is not the center (it is an extension)
newNode-center = false;
// link the new node to the old path
if (goingForward)
{
path-nextDirection = moveList[moveNum];
path-next = newNode;
newNode-prevDirection =
OppositeDirection(moveList[moveNum]);
newNode-prev = path;
newNode-next = nil;
newNode-nextDirection = noDirection;
} // end if
else
{
path-prevDirection = moveList[moveNum];
path-prev = newNode;
newNode-nextDirection =
OppositeDirection(moveList[moveNum]);
newNode-next = path;
newNode-prev = nil;
newNode-prevDirection = noDirection;
} // end else
// see if we are at the edge or can get to one
if (ExtendPathToEdge(boardSize, theBoard,
newNode, edge))
{
result = true;
} // end if
else
{
FreeBlock(newNode);
if (goingForward)
{
path-next = nil;
path-nextDirection = noDirection;
} // end if
else
{
path-prev = nil;
path-prevDirection = noDirection;
} // end else
} // end else
} // end if
} // end for

// return true if we succeeded, false if not
return result;
} // end ExtendPathToEdge

PrioritizeMoves
void PrioritizeMoves(Edge edge, Direction move[12])
{
switch (edge) {
case leftEdge:
// in order from most to least direct
move[0] = downLeftTwoBridge;
move[1] = upLeftTwoBridge;
move[2] = downTwoBridge;
move[3] = left;
move[4] = downLeft;
move[5] = upLeft;
move[6] = downRight;
move[7] = upRight;
move[8] = right;
move[9] = upTwoBridge;
move[10] = downRightTwoBridge;
move[11] = upRightTwoBridge;
break;
case rightEdge:
// in order from most to least direct
move[0] = upRightTwoBridge;
move[1] = downRightTwoBridge;
move[2] = upTwoBridge;
// determines whether a desired move is in a path
// PRECONDITIONS: path describes a path across the board;
// (row, col) defines the intended move
// POSTCONDITIONS: returns noDisruption if the move is not in the path,
// inTwoBridge if it threatens an established two-bridge, or inSpot if it
// occupies a location in the path (including a two-bridge whose end-points
// have not been secured)

Boolean TwoBridgeThreatened(long row, long col,
long threatRow, long threatCol, Direction move);
// determines whether a two-bridge is threatened by a given move
// PRECONDITIONS: (row, col) is the origin of a two-bridge; (threatRow, threatCol)
// is the new move; move is the direction of the two-bridge
// POSTCONDITIONS: returns true if the two-bridge is threatened by the move

void UpdatePath(Path *path, long row, long col);
// PRECONDITIONS: path points to a path across the board;
// (row, col) is the location of the move
// POSTCONDITIONS: the location in the path is marked as being occupied;
// sometimes, as when a two-bridge is filled in (and destroyed), an extra node
// is added to the path list

Direction GetDirection(long row1, long col1, long row2,
long col2);
// determines the direction from one piece to another
// PRECONDITIONS: (row1, col1) and (row2, col2) define two pieces
// POSTCONDITIONS: the direction from (row1, col1) to (row2, col2) is returned

Path *BetterPath(Path *path1, Path *path2,
PathAction action);
// determines which of two paths is superior to the other
// PRECONDITIONS: path1 and path2 point to paths
// POSTCONDITIONS: the better of the two paths is returned;
// if action is forgetBad, then the inferior path is disposed

long PathRating(Path *path);
// rates a path
// PRECONDITIONS: path is a path
// POSTCONDITIONS: a rating for the path is returned
// (always positive, low numbers are better)

void FillThreatenedTwoBridge(Path *path, long threatRow,
long threatCol, long *row, long *col);
// determines where to move in order to secure a threatened two-bridge
// PRECONDITIONS: path points to a path;
// (threatRow, threatCol) is the move which threatened the two-bridge
// POSTCONDITIONS: (row, col) is the move needed to secure
// the free half of the two-bridge

Path *TakeDetour(long boardSize, Chip *theBoard, Path *path,
long row, long col, Chip color);
// finds a new path after it has been disrupted
// PRECONDITIONS: path points to a path; (row, col)
// indicates a move which disrupted the path
// POSTCONDITIONS: the path is corrected, if possible, so that it avoids the
// opponent's piece, and it is then returned; nil is returned if no new path
// can be found

void FindBestMove(Path *ourPath, Path *oppPath, long *row,
long *col);
// TRIES to determine the best move
// PRECONDITIONS: ourPath and oppPath are the expected
// paths of the player and the opponent, respectively
// POSTCONDITIONS: (*row, *col) indicate the chosen move, which should be
// decent; if the opponent's path is better, it should be a defensive move; if
// not, it should be an offensive move; whenever possible, offensive and
// defensive moves are made to coincide with one another

Boolean NextToEdge(long row, long col, long boardSize,
Edge edge);
// determines if a piece is next to a given edge
// PRECONDITIONS: (row, col) is a piece; boardSize is the size of the board,
// edge is the edge we want to be near
// POSTCONDITIONS: returns true if the piece if one hex from the edge

Boolean Hex(long boardSize, long oppRow, long oppCol,
long *moveRow, long *moveCol, void *privStorage,
Boolean newGame, Boolean playFirst);

Hex
Boolean Hex(long boardSize, long oppRow, long oppCol,
long *moveRow, long *moveCol, void *privStorage,
Boolean newGame, Boolean playFirst)
{
// board storage (preserved between turns)
static Chip   *theBoard;
// expected paths (also preserved between turns)
static Path *ourPath, *oppPath;
// a temporary path used for comparisons
Path *newPath;
Disruption disruption; // holds path disruptions

if (newGame)
{
long i;

// initialize the private storage allocation system
InitializeHeap(privStorage, 0x100000); // 1 MB
// initialize storage space for the board
theBoard = AllocateBlock(boardSize * boardSize);
for (i = 0; i < boardSize * boardSize; i++)
theBoard[i] = empty;
// indicate that no paths have yet been determined
ourPath = oppPath = nil;
if (playFirst)
{
// go in the middle
*moveRow = (boardSize - 1) / 2;
*moveCol = boardSize / 2;
// mark the chip on the board
theBoard[*moveRow * boardSize + *moveCol] =
blue; // blue because we are moving first
// try to determine the shortest route across the board through the
// spot where we just moved
ourPath = BestPathAcrossBoard(boardSize,
theBoard, *moveRow, *moveCol, blue);
return true;
} // end if
} // end if
// check the opponent's move
if (!ValidMove(boardSize, theBoard, oppRow, oppCol))
// if it is illegal, abort here
return false;
// mark the opponent's move on the board
theBoard[oppRow * boardSize + oppCol] =
playFirst ? red : blue;
// if the opponent's move was in his path (offensive)

move[3] = right;
move[4] = upRight;
move[5] = downRight;
move[6] = upLeft;
move[7] = downLeft;
move[8] = left;
move[9] = downTwoBridge;
move[10] = upLeftTwoBridge;
move[11] = downLeftTwoBridge;
break;
case topEdge:
// in order from most to least direct
move[0] = upTwoBridge;
move[1] = upLeftTwoBridge;
move[2] = upRightTwoBridge;
move[3] = upLeft;
move[4] = upRight;
move[5] = left;
move[6] = right;
move[7] = downLeft;
move[8] = downRight;
move[9] = downLeftTwoBridge;
move[10] = downRightTwoBridge;
move[11] = downTwoBridge;
break;
case bottomEdge:
// in order from most to least direct
move[0] = downTwoBridge;
move[1] = downRightTwoBridge;
move[2] = downLeftTwoBridge;
move[3] = downRight;
move[4] = downLeft;
move[5] = right;
move[6] = left;
move[7] = upRight;
move[8] = upLeft;
move[9] = upRightTwoBridge;
move[10] = upLeftTwoBridge;
move[11] = upTwoBridge;
break;
default:
break; // should never arrive here
} // end switch
} // end PrioritizeMoves

PossibleMove
Boolean PossibleMove(long boardSize, Chip *theBoard,
long row, long col, Path *path, Direction move,
Chip color)
{
long newRow, newCol; // where the move leads

// determine where a move in the new direction would lead
FindNewLocation(row, col, move, &newRow, &newCol);
// the new location must be on the board and either
// empty or occupied by a friendly piece; it must also
// not be in the path already
if (!OnBoard(boardSize, newRow, newCol)
|| (theBoard[newRow * boardSize + newCol] ==
(color == blue ? red : blue)) ||
MoveInPath(path, newRow, newCol))
return false;
// if the move forms a two-bridge, there must
// be no pieces in between the two
if (IsTwoBridge(move))
{
return TwoBridgeFree(boardSize, theBoard, row, col,
move);
} // end if
else
return true;
} // end PossibleMove

FindNewLocation
void FindNewLocation(long row, long col, Direction move,
long *newRow, long *newCol)
{
// handle the row first
switch (move) {
case upTwoBridge:
*newRow = row - 2;
break;
case upRightTwoBridge:
case upRight:
case upLeft:
case upLeftTwoBridge:
*newRow = row - 1;
break;
case left:
case right:
*newRow = row;
break;
case downLeftTwoBridge:
case downLeft:
case downRight:
case downRightTwoBridge:
*newRow = row + 1;
break;
case downTwoBridge:
*newRow = row + 2;
break;
default: // should never get here
break;
} // end switch
// then handle the column
switch (move) {
case downLeftTwoBridge:
*newCol = col - 2;
break;
case upLeftTwoBridge:
case left:
case downLeft:
case downTwoBridge:
*newCol = col - 1;
break;
case upLeft:
case downRight:
*newCol = col;
break;
case upTwoBridge:
case upRight:
case right:
case downRightTwoBridge:
*newCol = col + 1;
break;
case upRightTwoBridge:
*newCol = col + 2;
break;
default: // should never get here
break;
} // end switch
} // end FindNewLocation

OppositeDirection
Direction OppositeDirection(Direction move)
{
switch (move) {
case upTwoBridge:
return downTwoBridge;
case upRightTwoBridge:
return downLeftTwoBridge;
case upRight:
return downLeft;
case upLeft:
return downRight;
case upLeftTwoBridge:
return downRightTwoBridge;
case left:
return right;
case right:
return left;
case downLeftTwoBridge:
return upRightTwoBridge;
case downLeft:
return upRight;
case downRight:
return upLeft;
case downRightTwoBridge:
return upLeftTwoBridge;
case downTwoBridge:
return upTwoBridge;
default: // should never get here
break;
} // end switch
} // end OppositeDirection

OnBoard
Boolean OnBoard(long boardSize, long row, long col)
{
return row = 0 && row < boardSize && col = 0 &&
col < boardSize;
} // end OnBoard

IsTwoBridge
Boolean IsTwoBridge(Direction move)
{
switch (move) {
case upTwoBridge:
case upRightTwoBridge:
case upLeftTwoBridge:
case downLeftTwoBridge:
case downRightTwoBridge:
case downTwoBridge:
return true;
default:
return false;
} // end switch
} // end IsTwoBridge

TwoBridgeFree
Boolean TwoBridgeFree(long boardSize, Chip *theBoard,
long row, long col, Direction move)
{
switch (move) {
case upTwoBridge:
return theBoard[(row - 1) * boardSize + col] ==
empty && theBoard[(row - 1) * boardSize +
col + 1] == empty;
case upRightTwoBridge:
return theBoard[(row - 1) * boardSize +
col + 1] == empty && theBoard[row *
boardSize + col + 1] == empty;
case upLeftTwoBridge:
return theBoard[(row - 1) * boardSize +
col] == empty && theBoard[row *
boardSize + col - 1] == empty;
case downLeftTwoBridge:
return theBoard[(row + 1) * boardSize +
col - 1] == empty && theBoard[row *
boardSize + col - 1] == empty;
case downRightTwoBridge:
return theBoard[(row + 1) * boardSize +
col] == empty && theBoard[row *
boardSize + col + 1] == empty;
case downTwoBridge:
return theBoard[(row + 1) * boardSize +
col] == empty && theBoard[(row + 1) *
boardSize + col - 1] == empty;
default:
return false;
} // end switch
} // TwoBridgeFree

PieceOnEdge
Boolean PieceOnEdge(long row, long col, long boardSize,
Edge edge)
{
switch (edge) {
case leftEdge:
return col == 0;
case rightEdge:
return col == boardSize - 1;
case topEdge:
return row == 0;
case bottomEdge:
return row == boardSize - 1;
default: // should never get here
break;
} // end switch
} // end PieceOnEdge

FreePath
void FreePath(Path *path)
{
if (!path)
return;
// go to the beginning of the path
for (; path-prev; path = path-prev);
// free each node until none are left
for (; path; path = path-next)
FreeBlock(path);
} // end FreePath

ValidMove
Boolean ValidMove(long boardSize, Chip *theBoard,
long row, long col)
{
return OnBoard(boardSize, row, col) &&
theBoard[row * boardSize + col] == empty; // free
} // end ValidMove

MoveInPath
Disruption MoveInPath(Path *path, long row, long col)
{
if (!path)
return noDisruption;

// go to the beginning of the path
for (; path-prev; path = path-prev);
// search the path until the end is reached or a node
// is found matching the desired move
for (; path; path = path-next)
// check for a threatened two-bridge
if (IsTwoBridge(path-nextDirection) &&
TwoBridgeThreatened(path-row, path-col,
row, col, path-nextDirection))
{
if (path-occupied && path-next-occupied)
return inTwoBridge;
else
return inSpot;
} // end if
else if (row == path-row && col == path-col)
return inSpot;
// if we get here, there are no disruptions
return noDisruption;
} // end MoveInPath

TwoBridgeThreatened
Boolean TwoBridgeThreatened(long row, long col,
long threatRow, long threatCol, Direction move)
{
switch (move) {
case upTwoBridge:
return (threatRow == row - 1) &&
(threatCol == col || threatCol == col + 1);
case upRightTwoBridge:
return (threatCol == col + 1) &&
(threatRow == row - 1 || threatRow == row);
case upLeftTwoBridge:
return (threatRow + threatCol == row + col - 1)
&& (threatRow == row || threatCol == col);
case downLeftTwoBridge:
return (threatCol == col - 1) &&
(threatRow == row || threatRow == row + 1);
case downRightTwoBridge:
return (threatRow + threatCol == row + col + 1)
&& (threatRow == row || threatCol == col);
case downTwoBridge:
return (threatRow == row + 1) &&
(threatCol == col || threatCol == col - 1);
default: // should not get here
return false;
} // end switch
} // end TwoBridgeThreatened

UpdatePath
void UpdatePath(Path *path, long row, long col)
{
// go to the beginning of the path
for (; path-prev; path = path-prev);
// search the path until the end is reached or a node
// is found matching the desired move
for (; path; path = path-next)
// check for completion of a two-bridge
if (IsTwoBridge(path-nextDirection) &&
TwoBridgeThreatened(path-row, path-col,
row, col, path-nextDirection))
{
// destroy the two-bridge and create two new connections
Path *newNode = AllocateBlock(sizeof (Path));

newNode-row = row;
newNode-col = col;
newNode-occupied = true;
newNode-center = false;
newNode-prevDirection = GetDirection(
row, col, path-row, path-col);
newNode-nextDirection = GetDirection(
row, col, path-next-row, path-next-col);
newNode-prev = path;
newNode-next = path-next;
path-nextDirection = OppositeDirection(
newNode-prevDirection);
path-next = newNode;
newNode-next-prevDirection =
OppositeDirection(newNode-nextDirection);
newNode-next-prev = newNode;

} // end if
else if (row == path-row && col == path-col)
path-occupied = true;
} // end UpdatePath

GetDirection
Direction GetDirection(long row1, long col1, long row2,
long col2)
{
// check for unique cases first
if (row2 == row1 + 2)
return downTwoBridge;
else if (row2 == row1 - 2)
return upTwoBridge;
else if (col2 == col1 + 2)
return upRightTwoBridge;
else if (col2 == col1 - 2)
return downLeftTwoBridge;
// then try the more common ones
else if (row2 == row1 - 1)
if (col2 == col1 - 1)
return upLeftTwoBridge;
else if (col2 == col1)
return upLeft;
else // col2 == col1
return upRight;
else if (row2 == row1 + 1)
if (col2 == col1 - 1)
return downLeft;
else if (col2 == col1 + 1)
return downRightTwoBridge;
else // col2 == col1
return downRight;
else // row2 == row1
if (col2 == col1 - 1)
return left;
else // col2 == col1 + 1
return right;
} // end GetDirection

BetterPath
Path *BetterPath(Path *path1, Path *path2,
PathAction action)
{
long rating1, rating2;
Path *betterPath, *worsePath;

// rate both paths
rating1 = PathRating(path1);
rating2 = PathRating(path2);
// compare the ratings (low is better)
if (rating1 < rating2)
{
betterPath = path1;
worsePath = path2;
} // end if
else
{
betterPath = path2;
worsePath = path1;
} // end else
// dispose of the bad path, if directed to do so
FreePath(worsePath);
return betterPath;
} // end BetterPath

PathRating
long PathRating(Path *path)
{
long rating;

if (!path)
return 4096;
// go to the beginning of the path
for (; path-prev; path = path-prev);
// count the number of unoccupied locations
for (rating = 0; path; path = path-next)
if (path-occupied == false)
rating++;
return rating;
} // end PathRating

FillThreatenedTwoBridge
void FillThreatenedTwoBridge(Path *path, long threatRow,
long threatCol, long *row, long *col)
{
// go to the beginning of the path
for (; path-prev; path = path-prev);
// scan through the path until the threat is found
for (; path; path = path-next)
if (IsTwoBridge(path-nextDirection) &&
TwoBridgeThreatened(path-row, path-col,
threatRow, threatCol, path-nextDirection))
{
// try all moves until we find one that fills
// the two-bridge (sorry, it's the easiest way
// way to do it)
Direction d;
Boolean done;

for (done = false, d = 0; !done &&
d < noDirection; d++)
{
FindNewLocation(path-row, path-col,
d, row, col);
// make sure we're not making the same move
// as the opponent
if (TwoBridgeThreatened(path-row,
path-col, *row, *col,
path-nextDirection) &&   (*row !=
threatRow || *col != threatCol))
{
done = true;
} // end if
} // end for
} // end if
} // end FillThreatenedTwoBridge

TakeDetour
Path *TakeDetour(long boardSize, Chip *theBoard, Path *path,
long row, long col, Chip color)
{
Boolean centerPassed; // have we passed the center?
Boolean blockFound; // have we located the disruption?
Path *corruptPath; // the part that was blocked
Edge edge;

// go to the beginning of the path
for (; path-prev; path = path-prev);
// find the location of the disruption
for (centerPassed = blockFound = false; path &&
!blockFound;)
{
if (path-center)
centerPassed = true;

if (IsTwoBridge(path-nextDirection) &&
TwoBridgeThreatened(path-row, path-col,
row, col, path-nextDirection))
{
if (centerPassed)
path = path-next;
blockFound = true;
} // end if
else if (row == path-row && col == path-col)
blockFound = true;
else
path = path-next;
} // end for
// free from there to the end
if (centerPassed)
{
corruptPath = path;
path = path-prev;
path-next = corruptPath-prev = nil;
FreePath(corruptPath);
} // end if
else
{
corruptPath = path;
path = path-next;
corruptPath-next = path-prev = nil;
FreePath(corruptPath);
} // end else
if (color == blue)
if (centerPassed)
edge = bottomEdge;
else
edge = topEdge;
else // color is red
if (centerPassed)
edge = rightEdge;
else
edge = leftEdge;
// extend the path from there to the edge
if (!ExtendPathToEdge(boardSize, theBoard, path, edge))
{
// if not possible, destroy the path
FreePath(path);
path = nil;
} // end if

return path;
} // end TakeDetour

FindBestMove
void FindBestMove(Path *ourPath, Path *oppPath, long *row,
long *col)
{
// ratings for our path, the opponent's path, and the
// two halves of the better (used) path
long ourRating, oppRating, prevRating = 0,
nextRating = 0;
Path *usedPath, *tempPath, *unusedPath;
// don't even try to continue if there are no paths
if (!oppPath && !ourPath)
return;
// see who has the better path
ourRating = PathRating(ourPath);
oppRating = PathRating(oppPath);
if (ourRating < oppRating) // ours is better
{
usedPath = ourPath;
unusedPath = oppPath;
}
else
{
usedPath = oppPath;
unusedPath = ourPath;
}
// first try to make a move which is both offensive and defensive
tempPath = usedPath;
// go to the beginning
for (; tempPath-prev; tempPath = tempPath-prev);
// find the first unoccupied piece
for (; tempPath && tempPath-occupied;
tempPath = tempPath-prev)
{
// see if it is in the other path, also
if (MoveInPath(unusedPath, tempPath-row,
tempPath-col))
{
*row = tempPath-row;
*col = tempPath-col;
return;
}
}
// look for unoccupied pieces
tempPath = usedPath;
// go to the beginning
for (; tempPath-prev; tempPath = tempPath-prev);
// go to the center
for (; !tempPath-center; tempPath = tempPath-next);
// rate the first half
for (; tempPath; tempPath = tempPath-prev)
prevRating += !tempPath-occupied;
tempPath = usedPath;
// go to the beginning
for (; tempPath-prev; tempPath = tempPath-prev);
// go back to the center
for (; !tempPath-center; tempPath = tempPath-next);
// rate the second half
for (; tempPath; tempPath = tempPath-next)
nextRating += !tempPath-occupied;
tempPath = usedPath;
// go to the beginning
for (; tempPath-prev; tempPath = tempPath-prev);
// go to the center
for (; !tempPath-center; tempPath = tempPath-next);
// make a move on the side with the worse (high) rating
if (prevRating  nextRating)
// find the first unoccupied piece
for (; tempPath && tempPath-occupied;
tempPath = tempPath-prev);
else
// find the first unoccupied piece
for (; tempPath && tempPath-occupied;
tempPath = tempPath-next);
if (tempPath)
{
*row = tempPath-row;
*col = tempPath-col;
} // end if
else // no unoccupied pieces anywhere
{
// if there are none, fill in any unconnected two-bridges
for (; usedPath-prev; usedPath =
usedPath-prev);
for (; usedPath && !IsTwoBridge(
usedPath-nextDirection);
usedPath = usedPath-next);
if (usedPath) // should always be true
{
// try all moves until we find one that
// fills the two-bridge (sorry, it's the
// easiest way way to do it)
Direction d;
Boolean done;

for (done = false, d = 0; !done &&
d < noDirection; d++)
{
FindNewLocation(usedPath-row,
usedPath-col, d, row, col);
if (TwoBridgeThreatened(usedPath-row,
usedPath-col, *row, *col,
usedPath-nextDirection))
{
done = true;
} // end if
} // end for
} // end if
} // end else
} // end FindBestMove

NextToEdge
Boolean NextToEdge(long row, long col, long boardSize,
Edge edge)
{
switch (edge) {
case leftEdge:
return col == 1;
case rightEdge:
return col == boardSize - 2;
case topEdge:
return row == 1;
case bottomEdge:
return row == boardSize - 2;
default: // should never get here
break;
} // end switch
} // end NextToEdge
Dynamic_Memory4.c
{
long
size;   // the size in bytes of the block

*prev,   // the previous block's header
*next;   // the next block's header

void *AllocateBlock(long size);
void FreeBlock(void *data);
void HeapSummary(void);
Boolean IsPointerValid(void *data);

*gHeapStart;

long
gFreeBlocks,
gUsedBlocks,
gFreeSpace,
gUsedSpace,
gTotalSpace;

void InitializeHeap
(
// these are assumed to be valid; no error-checking is performed
Header *heapStart,   // the address of the start of the heap zone
long   size      // the size of the zone
)
{
heapStart-size = size - sizeof (Header);
// mark the size of the zone
heapStart-prev = nil;       // mark as being the first block...
heapStart-next = nil;       // ...and the last
gHeapStart = heapStart;     // initialize the global heap start pointer
}
void ChopBlock
(
// these are assumed to be valid; fragSize must be less than theBlock-size
Header *theBlock,   // the block to chop
long fragSize         // the size of the first new fragment
)
{
*newBlock;

newBlock = (Header *) (((char *) theBlock) + sizeof (Header) + fragSize);
newBlock-size = theBlock-size - fragSize - sizeof (Header);
// the remaining space
newBlock-prev = theBlock;   // newBlock comes after theBlock
newBlock-next = theBlock-next;
// it gets inserted between theBlock and
// theBlock-next
if (theBlock-next)
theBlock-next-prev = newBlock;
theBlock-size = fragSize;   // theBlock gets just what was asked for
theBlock-next = newBlock;   // its new next block is newBlock
}

void *AllocateBlock
(
long   size      // the size of the desired block
)
{
const long
BLOCK_IN_USE_MASK = 0x80000000,   // if this bit is set in the 'size'
// field, the block is in use
MIN_BLOCK_SIZE = 80; // the smallest usable block (board data + pointers)

*currentBlock;   // a pointer to the block currently being considered

currentBlock = gHeapStart;

// loop until either there are no more blocks or a fitting one is found
while (currentBlock && ((currentBlock-size &
currentBlock = currentBlock-next;

if (currentBlock)   // a valid block was found
{
// if the block is much bigger than needed
if ((currentBlock-size - size)
ChopBlock(currentBlock, size);   // cut off a piece of exactly the                                                          // right size
currentBlock-size |= BLOCK_IN_USE_MASK; // mark as being in use

// return a pointer to just after the block header
return (char *) (currentBlock + 1);
}
else
// indicate that allocation failed
return nil;
}

void FuseBlocks
(
Header *block   // the block to fuse with its following neighbor
)
{
*neighbor;

neighbor = block-next;
block-next = neighbor-next;
neighbor-next-prev = block;
block-size += sizeof (Header) + neighbor-size;
// blocks must not be in use
}

void FreeBlock
(
void
*data   // the block of data to free, fusing with its neighbors if possible
)
{
const long
// bit in size field used to indicate use of blocks

*theBlock;      // the data block's header
// the header is located just before the data
theBlock = ((Header *) data) - 1;

// assumed to be in use, with flag set; here it is reset

// if there is a next block and it is free
if (theBlock-next &&
FuseBlocks(theBlock);

// if there is a previous block and it is free
if (theBlock-prev &&
FuseBlocks(theBlock-prev);

}

void HeapSummary
(
void
)
{
const long

*block;

block = gHeapStart;
while (block-next)
block = block-next;

gFreeBlocks = gUsedBlocks = gFreeSpace = gUsedSpace = 0;

while (block)
{
{
gUsedBlocks++;
}
else
{
gFreeBlocks++;
gFreeSpace += block-size;
}
block = block-prev;
}
gTotalSpace = (gFreeBlocks + gUsedBlocks) *
sizeof (Header) + gFreeSpace + gUsedSpace;
}
Boolean IsPointerValid(void *data)
{
*theBlock,
*compBlock;

theBlock = ((Header *) data) - 1;
compBlock = gHeapStart;

while(compBlock && compBlock != theBlock)
compBlock = compBlock-next;

if (compBlock == theBlock)
return true;
else
return false;

}

{
gHeapStart = start;
}

{
return gHeapStart;
}
Storage.h
{
long
size,         // the size in bytes of the block
inUse;

*prev,         // the previous block's header
*next,         // the next block's header
*prevFree,   // the previous free block
*nextFree;   // the next free block

void *AllocateBlock(long size);
void FreeBlock(void *data);
```

Community Search:
MacTech Search:

jAlbum Pro 12.6.4 - Organize your digita...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more
jAlbum 12.6.4 - Create custom photo gall...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results Simply drag and drop photos into groups, choose a design... Read more
Microsoft Remote Desktop 8.0.16 - Connec...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more
Spotify 1.0.4.90. - Stream music, create...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
djay Pro 1.1 - Transform your Mac into a...
djay Pro provides a complete toolkit for performing DJs. Its unique modern interface is built around a sophisticated integration with iTunes and Spotify, giving you instant access to millions of... Read more
Vivaldi 1.0.118.19 - Lightweight browser...
Vivaldi browser. In 1994, two programmers started working on a web browser. Our idea was to make a really fast browser, capable of running on limited hardware, keeping in mind that users are... Read more
Stacks 2.6.11 - New way to create pages...
Stacks is a new way to create pages in RapidWeaver. It's a plugin designed to combine drag-and-drop simplicity with the power of fluid layout. Features: Fluid Layout: Stacks lets you build pages... Read more
xScope 4.1.3 - Onscreen graphic measurem...
xScope is powerful set of tools that are ideal for measuring, inspecting, and testing on-screen graphics and layouts. Its tools float above your desktop windows and can be accessed via a toolbar,... Read more
Cyberduck 4.7 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Labels & Addresses 1.7 - Powerful la...
Labels & Addresses is a home and office tool for printing all sorts of labels, envelopes, inventory labels, and price tags. Merge-printing capability makes the program a great tool for holiday... Read more

## Latest Forum Discussions

This Week at 148Apps: April 20-24, 2015
The Apps of April How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you're looking for. The ones we love become Editor’s Choice, standing out above the many... | Read more »
Discover Your Reflexes With Minimalist G...
Discover O, BYOF Studios, may look simple at first with its' color matching premise and swipe controls, but as you speed up the task becomes more daunting. [Read more] | Read more »
Here's Another Roundup of Notable A...
Now that the Apple Watch is publically available (kind of), even more apps and games have been popping up for it. Some of them are updates to existing software, others are brand new. The main thing is that they're all for the Apple Watch, and if you... | Read more »
Use Batting Average and the Apple Watch...
Batting Average, by Pixolini, is designed to help you manage your statistics. Every time you go to bat, you can use your Apple Watch to track  your swings, strikes, and hits. [Read more] | Read more »
Celebrate Studio Pango's 3rd Annive...
It is time to party, Pangoland pals! Studio Pango is celebrating their 3rd birthday and their gift to you is a new update to Pangoland. [Read more] | Read more »
Become the World's Most Important D...
Must Deliver, by cherrypick games, is a top-down endless-runner witha healthy dose of the living dead. [Read more] | Read more »
SoundHound + LiveLyrics is Making its De...
SoundHound Inc. has announced that SoundHound + LiveLyrics, will be one of the first third-party apps to hit the Apple Watch. With  SoundHound you'll be able to tap on your watch and have the app recognize the music you are listening to, then have... | Read more »
Adobe Joins the Apple Watch Lineup With...
A whole tidal wave of apps are headed for the Apple Watch, and Adobe has joined in with 3 new ways to enhance your creativity and collaborate with others. The watch apps pair with iPad/iPhone apps to give you total control over your Adobe projects... | Read more »
Z Steel Soldiers, Sequel to Kavcom'...
Kavcom has released Z Steel Soldiers, which continues the story of the comedic RTS originally created by the Bitmap Brothers. [Read more] | Read more »
Seene Lets You Create 3D Images With You...
Seene, by Obvious Engineering, is a 3D capture app that's meant to allow you to create visually stunning 3D images with a tap of your finger, and then share them as a 3D photo, video or gif. [Read more] | Read more »

## Price Scanner via MacPrices.net

Final day for Best Buy’s 4 Day Sale: Up to \$3...
Best Buy has the new 2015 13″ 1.6GHz/128GB MacBook Air on sale for \$799.99 through April 27th. That’s \$200 off MSRP, and it’s the lowest price available for this new model from any reseller. Choose... Read more
College Student Deals: Additional \$50 off Mac...
Take an additional \$50 off all MacBooks and iMacs at Best Buy Online with their College Students Deals Savings, valid through May 9, 2015. Anyone with a valid .EDU email address can take advantage of... Read more
Save up to \$300 on a new Mac, \$30 on an iPad,...
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
Zoho Business Apps for Apple Watch Put Select...
Pleasanton, California based Zoho has launched Zoho Business Apps for Apple Watch, a line of apps that extends Zoho business applications to let users perform select functions from an Apple Watch.... Read more
Universal Stylus Initiative Launched to Creat...
OEMs, stylus and touch controller manufacturers have announced the launch of Universal Stylus Initiative (USI), a new organization formed to develop and promote an industry specification for an... Read more
Amazon Shopping App for Apple Watch
With the new Amazon shopping app for Apple Watch, Amazon customers with one of the wearable devices can simply tap the app on the watch to purchase items in seconds, or save an idea for later. The... Read more
Mac Pros on sale for up to \$260 off MSRP
B&H Photo has Mac Pros on sale for up to \$260 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: \$2799, \$200 off MSRP - 3.5GHz 6-core Mac Pro: \$3719.99... Read more
Apple refurbished Time Capsules available for...
The Apple Store has certified refurbished Time Capsules available for \$100 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: \$199, \$100... Read more
Intel Compute Stick: A New Mini-Computing For...
The Intel Compute Stick, a new pocket-sized computer based on a quad-core Intel Atom processor running Windows 8.1 with Bing, is available now through Intel Authorized Dealers across much of the... Read more
Heal to Launch First One-Touch House Call Doc...
Santa Monica, California based Heal, a pioneer in on-demand personal health care services — will offer the first one-touch, on-demand house call doctor app for the Apple Watch. Heal’s Watch app,... Read more

## Jobs Board

*Apple* iOS Specialist - TCML (United States...
AppleiOS Specialist Senior Apple /iOS Administrator/Engineer responsible for configuration and distribution of desktop, laptop and mobile devices to State Employees Read more
*Apple* Client Systems Solution Specialist -...
…drive revenue and profit in assigned sales segment and/or region specific to the Apple brand and product sets. This person will work directly with CDW Account Managers 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* Support Technician IV - Jack Henry a...
Job Description Jack Henry & Associates is seeking an Apple Support Technician. This position while acting independently, ensures the proper day-to-day control of Read more
*Apple* Client Systems Solution Specialist -...
…drive revenue and profit in assigned sales segment and/or region specific to the Apple brand and product sets. This person will work directly with CDW Account Managers Read more