July 01 Challenge
Volume Number: 17 (2001)
Issue Number: 07
Column Tag: Programmer's Challenge
by Bob Boonstra, Westford, MA
Down-N-Out
George Warner earns two Challenge points for suggesting another interesting board game, this time the solitaire game known as Down-N-Out. The Down-N-Out board is a 10x30 rectangular array of cells, initially populated randomly with 100 cells of each of three colors. The object is to score as many points as possible by removing cells from the board. A cell can be removed if it is adjacent (horizontally or vertically, but not diagonally) with a cell of the same color. When a cell is removed, all cells connected to it by transitive adjacency are removed. That is, all adjacent cells are removed, and all cells adjacent to those cells, etc. The number of points earned for each move is equal to the square of the number of cells removed (e.g., 2 cells = 4 points, 3 cells = 9 points, etc.). There is an obvious advantage to planning moves that maximize the number of connected cells removed simultaneously. After each move, the board is compacted by sliding all cells downward to fill any empty cells, and then by sliding all columns to the center to fill any empty columns. The game continues as long as cells can be removed.
For those of you interested in trying the game, there is a shareware version available at
http://www.peciva.com/software/downout.shtml.
The prototype for the code you should write is:
typedef char CellColor; /* 0==empty, 1..numColors are valid colors */
void InitDownNOut(
short boardSizeRows, /* number of rows in the game */
short boardSizeCols, /* number of columns in the game */
short numColors, /* number of colors in the game */
WindowPtr wdw /* window where results of your moves should be displayed */
);
void HandleUpdateEvent(EventRecord theEvent);
Boolean /* able to play */ PlayOneDownNOutMove(
CellColor board[], /* board[row*boardSizeCols + col] is color of cell at [row][col] */
long score, /* points earned prior to this move */
short *moveRow, /* return row of your next move */
short *moveCol /* return col of your next move */
);
void TermDownNOut(void);
Each game begins with a call to your InitDownNOut routine, where you are given the dimensions of the game board (boardSizeRows and boardSizeCols), the number of colors in the game (numColors), and a pointer (gameWindow) to a WindowRecord where you must display the game state as it progresses. Finally, you will be given the initial state of the game board, fully populated with equal numbers of each color cell, subject to rounding limitations. InitDownNOut should allocate any dynamic memory needed by your solution, and that memory should be returned at the end of the game when your TermDownNOut routine is called.
Your PlayOneDownNOutMove routine will be called repeatedly, once for each move you make. You will be given your current point score as calculated by the test code and the state of the game board. You should determine the most advantageous move and return it in moveRow and moveCol. You should update the game board, eliminating cells removed by your move and compacting the board vertically and then horizontally. You should calculate the number of cells removed and return it in numberOfCellsRemoved.
The last time we ran a Challenge that involved maintaining a display, contestants asked how the window would be redrawn in response to an update event. This time, I'm asking you to write a routine to do that. Your HandleUpdateEvent routine will be called by the test code whenever an update event is received for your gameWindow.
During the call to InitDownNOut, and after each of your moves, you should display the updated game state in the gameWindow. The details of the display are up to you, as long as the display correctly and completely represents the state of the board.
The winner will be the best scoring entry, as determined by the sum of the point score of each game, minus a penalty of 1% for each millisecond of execution time used for that game. The Challenge prize will be divided between the overall winner and the best scoring entry from a contestant that has not won the Challenge recently.
This will be a native PowerPC Challenge, using the CodeWarrior Pro 6 environment. Solutions may be coded in C or C++. I've deleted Pascal from the list of permissible languages, both because it isn't supported by CW6 (without heroics) and because no one has submitted a Pascal solution in a long time.
Three Months Ago Winner
Congratulations to Ernst Munter (Kanata, Ontario, Canada) for submitting the best scoring solution in the April Crossword II Challenge. This Challenge was inspired by a classroom exercise to construct a 20x20 crossword puzzle using the names of the elements in the periodic table, valuing each word according to the atomic number of the corresponding element, with the objective of maximizing the total value of the puzzle. We generalized the problem by making the word list, word values, and puzzle size parameters of the problem. And to incorporate the usual emphasis on efficiency, we penalized each test case by 1% for each minute of execution time required to generate the puzzle.
The winning solution starts by assigning a strength value to each word in the word list. The strength of a word is a scaled version of the value assigned by the problem input, divided by the length of a word. This heuristic favors shorter words of a given value over longer words of the same value. Then the Board::Solve routine tries to place words until a time limit (set to 15 seconds) expires or there are no more valid moves to explore. The moves are attempted in order of decreasing value, where the value of a move is the assigned value of word being placed, divided by the length of the word minus the number of letters that intersect other words. Again, this gives priority to placement of shorter high value words over longer ones, and to placements that efficiently use the board space by intersecting other words.
I evaluated the four entries received using a set of ten test cases ranging in size from 20x20 to 50x50. Ernst's solution packed 10% more word value into his puzzles than the second place entry by Ron Nepsund, taking significantly more execution time as well. For the original 20x20 problem based on the periodic table, Ernst's entry produced the following crossword, valued at 2470 points:
LAWRENCIUM__XENON_P_
_S__E______B______L_
_T___O_____AMERICIUM
_ACTINIUM__R______T_
_T______E__I___ARGON
SILVER_ERBIUM___H_N_
_N______C__M____E_I_
_E__BISMUTH_POLONIUM
________R__G____I_M_
_F_C____Y__O_R__U___
_E_A_C_____LEADM_U__
_RADIUM__T_D_D_B__R_
_M_M_R___H___O_E__A_
_IRIDIUM_O_TIN_R__N_
_U_U_U___R_____K__I_
_M_M_M_I_I__NOBELIUM
_______R_U_____L__M_
CERIUM_OSMIUM__ZINC_
_______N________U___
HAFNIUM__FRANCIUM___
|
Ernst would have won by an even wider margin were it not for an ambiguity in the problem statement. The problem specified that each word could only occur once in the puzzle, and that each sequence of letters in the puzzle had to form a word. What I meant to say, however, but didn't, was that each word in the puzzle needed to be distinct. Two of the contestants took advantage of this loophole, for example, to claim credit for the word "tin" embedded in the longer word "actinium". Fortunately for my sense of fairness if nothing else, when I ran the tests both allowing and not allowing the loophole, the scores were such that the ranking of the entries was unchanged. The results as presented reflect the actual wording of the puzzle, and allow a word to be embedded in another word.
As the best-placing entry from someone who has not won a Challenge in the past two years, Ron Nepsund wins a share of this month's Challenge prize. You don't need to defeat the Challenge points leaders to claim a part of the prize, so enter the Challenge and win Developer Depot credits!
The table below lists, for each of the solutions submitted, the number of points earned by each entry, and the total time in seconds. It also lists the code size, data size, and programming language used for each entry. As usual, the number in parentheses after the entrant's name is the total number of Challenge points earned in all Challenges prior to this one.
Name | | Points | Time(secs) | Code Size |
| | | |
Ernst Munter(731) | 52378 | 151.4 | 3940 |
Ron Nepsund(47) | 47489 | 6.7 | 44520 |
Jan Schotsman(7) | 44888 | 32.9 | 12708 |
Ken Slezak(26) | [LATE] | 4927937.4 | 3160 |
Name | Data Size | Lang |
Ernst Munter | 174 | C++ |
Ron Nepsund | 6530 | C++ |
Jan Schotsman | 448 | C++ |
Ken Slezak | 47 | C++ |
Top Contestants...
Listed here are the Top Contestants for the Programmer's Challenge, including everyone who has accumulated 20 or more points during the past two years. The numbers below include points awarded over the 24 most recent contests, including points earned by this month's entrants, the number of wins over the past 24 months, and the total number of career Challenge points.
Rank | Name | | Points(24 mo) |
1. | Munter, Ernst | | 304 |
2. | Rieken, Willeke | | 83 |
3. | Saxton, Tom | | 76 |
4. | Taylor, Jonathan | | 56 |
5. | Shearer, Rob | | 55 |
6. | Wihlborg, Claes | | 49 |
7. | Maurer, Sebastian | | 48 |
Name | Wins(24 mo) | Total Points |
Munter, Ernst | 12 | 751 |
Rieken, Willeke | 3 | 134 |
Saxton, Tom | 2 | 185 |
Taylor, Jonathan | 2 | 56 |
Shearer, Rob | 1 | 62 |
Wihlborg, Claes | 2 | 49 |
Maurer, Sebastian | 1 | 108 |
...and the Top Contestants Looking for a Recent Win
In order to give some recognition to other participants in the Challenge, we also list the high scores for contestants who have accumulated points without taking first place in a Challenge during the past two years. Listed here are all of those contestants who have accumulated 6 or more points during the past two years.
Rank | Name | Points | Points |
| | (24 mo) | Total |
8. | Boring, Randy | 32 | 142 |
9. | Schotsman, Jan | 14 | 14 |
10. | Sadetsky, Gregory | 12 | 14 |
11. | Nepsund, Ronald | 10 | 57 |
12. | Day, Mark | 10 | 30 |
13. | Jones, Dennis | 10 | 22 |
14. | Downs, Andrew | 10 | 12 | |
15. | Duga, Brady | 10 | 10 | |
16. | Fazekas, Miklos | 10 | 10 | |
17. | Flowers, Sue | 10 | 10 | |
18. | Strout, Joe | 10 | 10 | |
19. | Nicolle, Ludovic | 7 | 55 | |
20. | Hala, Ladislav | 7 | 7 | |
21. | Miller, Mike | 7 | 7 | |
22. | Widyatama, Yudhi | 7 | 7 | |
23. | Heithcock, JG | 6 | 43 | |
There are three ways to earn points: (1) scoring in the top 5 of any Challenge, (2) being the first person to find a bug in a published winning solution or, (3) being the first person to suggest a Challenge that I use. The points you can win are:
1st place | | 20 points |
2nd place | | 10 points |
3rd place | | 7 points |
4th place | | 4 points |
5th place | | 2 points |
finding bug | | 2 points |
suggesting Challenge | | 2 points |
Here is Ernst's winning CrosswordII solution:
CrosswordII.cp
Copyright © 2001
Ernst Munter, Kanata, ON, Canada
To avoid any significant point penalty (of 1% per minute), processing stops
after 15 seconds.
A private copy of the puzzle is built where each cell is an unsigned character,
with value of 0, c, or 2*c. An empty cell is 0, an placing a word is done
by adding each of the word’s character into the corresponding cell. Similarly,
removal of a word is done with subtraction.
*/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <Events.h>
#include “CrosswordII.h”
typedef unsigned long ulong;
typedef unsigned short ushort;
typedef unsigned char uchar;
static int N=0;
enum {
kDown = 0,
kAcross = 1,
kMaxMoves = 5,
kTicksPerSecond = 60,
kMaxSeconds = 15
};
struct MyWord
struct MyWord
// Encapsulation of Words
{
const Words* word;
ulong length;
ulong strength;// length-relative value
bool used;
MyWord(){}
MyWord(const Words* wp) :
word(wp),
length(strlen(wp->theWord)),
strength((0x10000L*wp->value)/(1+length)),
used(false)
{}
const Words* Word() const {return word;}
const char* Chars() const {return word->theWord;}
long Value() const {return word->value;}
int Length() const {return length;}
bool IsAvailable() const {return !used;}
void SetUsed() {used = true;}
void ClearUsed() {used = false;}
ulong Strength() const {return strength;}
};
static int CmpWord(const void* a,const void* b)
{
MyWord* ap=(MyWord*)a;
MyWord* bp=(MyWord*)b;
return bp->strength - ap->strength;
}
struct MyMove
// A Move is a placement of a word
{
MyWord* w;
ulong value;
ushort row;
ushort col;
ushort delta;
ushort size;
ulong Value() const {return value;}
ulong Points() const {return w->word->value;}
void Init(int numIntersects,MyWord* wx,
int r,int c,int d,int s)
{
w=wx;
value=(0x10000 * w->word->value) /
(1+w->Length()-numIntersects);
row=r;
col=c;
delta=d;
size=s;
}
void Clear() {value=0;}
ulong IsValid() const {return value;}// != 0
void Convert(const Words* words,WordPositions* p)
// Converts this instance of “MyMove” to a “WordPosition” as defined in
// “CrosswordII.h”
{
p->whichWord=w->word-words;
p->row=row;
p->col=col;
p->orientation=(delta==1)?kAcross:kDown;
}
void RemoveWord(char* puzzle)
{
char* p=puzzle+row*size+col;
char* str=w->word->theWord;
for (int i=0;i<w->Length();i++)
{
*p -= *str++;
p+=delta;
}
w->ClearUsed();
}
void PlaceWord(char* puzzle)
{
char* p=puzzle+row*size+col;
char* str=w->word->theWord;
for (int i=0;i<w->Length();i++)
{
*p += *str++;
p+=delta;
}
w->SetUsed();
}
int IntersectAcross(MyWord* w,int r,int c,
char* puzzle,int puzzleSize)
{
// returns -1(no fit), 0 (fit, no intersects) or n>0 (n intersects with other words)
// insertion point p
char* p=puzzle+r*puzzleSize+c;
int len=w->Length();
// cell before the word must be a border or blank
char* rowStart=puzzle+r*puzzleSize;
char* cellBefore=p-1;
if ((cellBefore >= rowStart) && (0 != *cellBefore))
return -1;
// cell after the word must be a border or blank
char* rowEnd=rowStart+puzzleSize;
char* cellAfter=p+len;
if ((cellAfter < rowEnd) && (0 != *cellAfter))
return -1;
// all cells to the side of the word must be
// (a) either blank
// (b) or part of a crossing word
// we know case b applies only if the cell the current word is
// to occupy is already occupied - with a letter equal to str[x]
char* str=w->word->theWord;
char* puzzleEnd=puzzle+puzzleSize*puzzleSize;
int numIntersects=0;
for (int i=0;i<len;i++,str++,p++)
{
if (*p == 0)// crossing a blank
{
// cell above must be outside border, or blank
char* cellAbove=p-puzzleSize;
if ((cellAbove >= puzzle) && (0 != *cellAbove))
return -1;
// cell below must be outside border, or blank
char* cellBelow=p+puzzleSize;
if ((cellBelow < puzzleEnd) && (0 != *cellBelow))
return -1;
} else if (*p == *str)// crossing a word, matching
{
numIntersects++;
} else // crossing, but no match
{
return -1;
}
}
Init(numIntersects,w,r,c,1,puzzleSize);
return numIntersects;
}
int IntersectDown(MyWord* w,int r,int c,
char* puzzle,int puzzleSize)
{
// returns -1(no fit), 0 (fit, no intersects) or n>0 (n intersects with other words)
// insertion point p
char* p=puzzle+r*puzzleSize+c;
int len=w->Length();
// cell before the word must be a border or blank
char* colStart=puzzle+c;
char* cellBefore=p-puzzleSize;
if ((cellBefore >= colStart) && (0 != *cellBefore))
return -1;
// cell after the word must be a border or blank
char* bottomBorder=puzzle+puzzleSize*puzzleSize;
char* cellAfter=p+len*puzzleSize;
if ((cellAfter < bottomBorder) && (0 != *cellAfter))
return -1;
// all cells to the side of the word must be
// (a) either blank
// (b) or part of a crossing word
// we know case b applies only if the cell the current str would
// occupy is already occupied - with a letter equal to str[x]
char* str=w->word->theWord;
char* puzzleEnd=puzzle+puzzleSize*puzzleSize;
char* leftEdge=puzzle+r*puzzleSize;
int numIntersects=0;
for (int i=0; i<len;
i++,str++,p+=puzzleSize,leftEdge+=puzzleSize)
{
if (*p == 0)// crossing a blank
{
// cell on the left must be the left border, or blank
char* cellLeft=p-1;
if ((cellLeft >= leftEdge) && (0 != *cellLeft))
return -1;
// cell on right must be on the right edge, or blank
char* cellRight=p+1;
char* rightEdge=leftEdge+puzzleSize;
if ((cellRight < rightEdge) && (0 != *cellRight))
return -1;
} else if (*p == *str)// crossing a word, matching
{
numIntersects++;
} else // crossing, but no match
{
return -1;
}
}
Init(numIntersects,w,r,c,puzzleSize,puzzleSize);
return numIntersects;
}
};
typedef MyMove* MyMovePtr;
inline bool operator > (const MyMove & a,const MyMove & b)
{
return a.Value() > b.Value();
}
struct MyMoveArray
struct MyMoveArray
{
int numMoves;
int maxMoves;
MyMove moves[kMaxMoves];
MyMoveArray(int max) :
numMoves(0),
maxMoves(max)
{}
int NumMoves() const {return numMoves;}
MyMove* Moves() {return moves;}
void Insert(MyMove & m)
{
if (numMoves==0)
{
numMoves=1;
moves[0]=m;
} else if (numMoves<maxMoves)
{
MyMove* mx=moves+numMoves;
while ((mx>moves) && (*(mx-1) > m))
{
*mx=*(mx-1);
mx=mx-1;
}
*mx=m;
numMoves++;
} else if (m > moves[numMoves-1])
{
numMoves—;
Insert(m);
}
}
};
struct Board
struct Board
{
long puzzleSize;
char* puzzle;
long numWords;
MyWord* myWords;
long numPositions;
WordPositions* bestPositions;
MyMove* movePool; // single pool allocated for movelists
MyMove* endMovePool;
MyMovePtr* moveStack; // move stack tracks the history of executed moves
MyMovePtr* moveStackPointer;
MyMovePtr* lastMoveStack;
Board(long pSize,const Words* words,long nWords) :
puzzleSize(pSize),
puzzle(new char[(pSize)*(pSize)]),
numWords(nWords),
myWords(new MyWord[nWords]),
numPositions(0),
bestPositions(new WordPositions[numWords]),
movePool(new MyMove[numWords*kMaxMoves]),
endMovePool(movePool+numWords*kMaxMoves),
moveStack(new MyMovePtr[numWords]),moveStackPointer(moveStack),
lastMoveStack(moveStack+numWords-1)
{
for (long i=0;i<numWords;i++)
myWords[i]=MyWord(words+i);
// sort words by strength
qsort(myWords,numWords,sizeof(MyWord),CmpWord);
// remove all 0-value words
long i=numWords;
while ((i>0) && (myWords[i-1].Value()<=0))
i=i-1;
numWords=i;
}
~Board()
{
delete [] bestPositions;
delete [] myWords;
delete [] puzzle;
}
void Clear()
{
memset(puzzle,0,sizeof(char)*(puzzleSize)*(puzzleSize));
}
int Solve(const Words* words,WordPositions* positions);
void SetPosition(const Words* words,MyWord* w,WordPositions* pos,
int row,int col,int o)
{
pos->whichWord=w->Word()-words;
pos->row=row;
pos->col=col;
pos->orientation=o;
}
void PushMove(MyMove* mp){
*moveStackPointer++=mp;
}
MyMove* PopMove()
{
return *—moveStackPointer;
}
MyMove* GenerateMoveList(MyMove* mp)
{
// Lists all legal moves in a list, starting with a null-move;
// sorts the moves and returns the highest value move on the list
// Each move is given a “value” reflecting its relative merit.
if (mp+kMaxMoves >= endMovePool)
return 0; // no room for movelist, should not really happen
// but if it does, we just have to backtrack
MyMove m;
int i,row,col,maxRow,maxCol,drow,dcol;
// create moves
MyMoveArray ma(kMaxMoves);
MyWord* w=myWords;
ulong bestStrength=0;
for (i=0;i<numWords;i++,w++)
{
if (!w->IsAvailable()) continue;
ulong strength=w->Strength();
if (strength < bestStrength) continue;
maxCol=maxRow=puzzleSize-w->Length();
// find every legal position
drow=0;
for (row=puzzleSize/2;(row>=0)&&(row<puzzleSize);row+=drow)
{
dcol=0;
for (col=puzzleSize/2;(col>=0) && (col<puzzleSize);col+=dcol)
{
if ((col<=maxCol) &&
(m.IntersectAcross(w,row,col,puzzle,puzzleSize)>=0))
{
ma.Insert(m);
bestStrength=strength;
}
if ((row<=maxRow) &&
(m.IntersectDown(w,row,col,puzzle,puzzleSize)>=0))
{
ma.Insert(m);
bestStrength=strength;
}
if (dcol>=0) dcol=-1-dcol; else dcol=1-dcol;
}
if (drow>=0) drow=-1-drow; else drow=1-drow;
}
}
// put a sentinel 0-move at the start of the movelist
mp->Clear();
// copy moves from the moves array into the movelist space
MyMove* mx=ma.Moves();
for (int i=0;i<ma.NumMoves();i++)
*(++mp) = *mx++;
return mp;
}
long Execute(MyMove* mp)
{
mp->PlaceWord(puzzle);
PushMove(mp);
return mp->Points();
}
MyMove* Undo(long & points)
// Undoes the last stacked move, returns this move, or 0 if no move found
{
MyMove* mp=PopMove();
if (mp==0) return mp;
mp->RemoveWord(puzzle);
points -= mp->Points();
return mp;
}
long CopyMovesBack(const Words* words,WordPositions* positions)
// Scans the movestack, converts MyMoves to positions.
// Returns the number of positions
{
int numMoves=0;
for (MyMovePtr* index=moveStack+1;index<moveStackPointer;index++)
{
MyMove* mp=*index;
mp->Convert(words,positions+numMoves);
numMoves++;
}
return numMoves;
}
};
Board::Solve
int Board::Solve(const Words* words,WordPositions* positions)
{
WordPositions* pos=positions;
long numPositions=0;
long bestPoints=0;
long start=TickCount();
Clear();
moveStackPointer=moveStack;
// Put a sentinel null move at start of move stack
PushMove(0);
MyMove* moveList=movePool;
long points=0;
MyMove* nextMove=GenerateMoveList(moveList);
// moveList to nextMove defines a movelist which always starts with a 0-move
// and is processed in order nextMove, nextMove-1, ... until 0-move is found
if (!nextMove)
return 0;
for (;;)
{
while (nextMove && nextMove->IsValid())
{
points+=Execute(nextMove);
if (points > bestPoints)
{
bestPoints=points;
numPositions=CopyMovesBack(words,positions);
}
moveList=1+nextMove;
long numTicks=TickCount()-start;
if (numTicks>kMaxSeconds*kTicksPerSecond)
break;
nextMove=GenerateMoveList(moveList);
} // end while
do {
MyMove* prevMove=Undo(points);
if (!prevMove) // stack is completely unwound, exhausted
break;
// try to use the last move:
nextMove = prevMove-1;
} while (!nextMove->IsValid());
moveList=nextMove;
while ((moveList>=movePool) && (moveList->IsValid()))
moveList—;
if (moveList<=movePool)
break;
}
return numPositions;
}
CrosswordII
short /* numberOfWordPositions */ CrosswordII (
short puzzleSize, /* puzzle has puzzleSize rows and columns */
const Words words[], /* words to be used to form the puzzle */
short numWords, /* number of words[] available */
WordPositions positions[] /* placement of words in puzzle */
) {
if (numWords <= 0)
return 0;
Board B(puzzleSize,words,numWords);
long numberOfWordPositions=B.Solve(words,positions);
return numberOfWordPositions;
}