![](/file/12652/www.mactech.com.tar/www.mactech.com/sites/all/themes/custom_front/images/you_are_here_red.gif)
![](/file/12652/www.mactech.com.tar/www.mactech.com/sites/default/files/beta-site.gif)
|
Volume Number: 17 (2001)
Issue Number: 11
Column Tag: Programmer's Challenge
by Bob Boonstra, Westford, MA
Seega
While rummaging through a dresser drawer, I ran across a collection of magnetic board games put out by a company called Midnite Snack, www.magneticgames.com. The company advertises them as ancient games from all over the world. I don't know how popular these games are across the world, but some of them looked like they might make interesting Challenge problems. This month, your Challenge is to write code that plays the game Seega.
The prototype for the code you should write is:
typedef struct Position { int row; /* 0..boardSize-1 */ int col; /* 0..boardSize-1 */ } Position; typedef struct Board { int boardSize; /* odd integer >= 5 */ char cell[]; /* board Position (row,col) is cell[ row*boardSize + col ] */ /* cell[]==0 is an empty cell */ } Board; void InitGame( int boardSize; /* number of rows and columns, odd integer >= 5 */ char pieceValue; /* value assigned to your pieces, 1..numberOfPlayers */ Boolean playFirst; /* TRUE if you place pieces first (and move second) */ int stalemateThreshold; /* stalemate will be declared after this number of moves without a capture */ ); void PlacePieces( const Board board; /* board state before you place pieces */ Position *placePiece1; /* place a piece at *placePiece1 */ Position *placePiece2; /* place a piece at *placePiece2 */ ) void MovePiece( const Board board; /* board state before you move a piece, updated by test code */ Boolean followUpMove; /* TRUE if you must make another capture with the last piece moved */ Position *moveFrom; /* location you are moving from, (-1,-1) if you cannot move */ Position *moveTo; /* location you are moving to, (-1,-1) if you cannot move */ Boolean *blocked; /* return TRUE if you cannot move */ ); void TermGame(void);
Seega is played on a 5x5 board, which we will be generalizing to an nxn board, for odd values of n no smaller than 5. Each player has 12 pieces, or in the general case, (nxn-1)/2 pieces. The game is played in two phases. In the first phase, players take turns placing two pieces anywhere on the board except for the center square. After both players have placed all of their pieces on the board, the player who last placed a piece moves one piece horizontally or vertically (not diagonally). An opponent's pieces are captured when they are between, horizontally or vertically, the piece moved by the player and another of the player's pieces. More than one piece can be captured on a single move. When a player captures one or more of his/her opponent's pieces, the capturing player makes another move if another capture can be made with the same piece. No piece in the center of the board may be captured. A piece that is moved between two opponent pieces is not captured. If a player cannot move, it becomes the opponent's turn to move again. The player who captures all of his opponent's pieces wins the game. In the event both players retain pieces, and no more captures can be made, the player with the most pieces on the board wins the game.
Your InitGame routine will be called with the game parameters, the size of the board (boardSize), the value assigned to your pieces (pieceValue), whether you will be the first person to place pieces on the board (playFirst), and the number of moves without a capture before a stalemate is declared (stalemateThreshold).
When it is your turn to place pieces on the board during the first phase of the game, your PlacePieces routine will be called. You will be given the current state of the board, and should return the locations of the next two pieces you place on the board.
Your MovePiece routine will be called when it is your turn to move. Again, you will be given the current state of the board. You should return the location of the piece that you chose to move, and the location you move it to. The test code will remove any pieces captured by your opponent, and call MovePiece again if another capture can be made by the piece you moved. If your code is called to make another move with the same piece, the flag followUpMove will be TRUE.
When a game is over, your TermGame routine will be called. You should return any dynamically allocated memory and perform any other necessary cleanup.
Any illegal move will result in loss of the game. Illegal moves include attempting to move a piece from a cell where you do not have a piece, or attempting to move to an occupied square, or a followUpMove with a different piece than moved previously.
Entries will be evaluated by conducting a round-robin or other fair tournament. Each entry will be given the same number of opportunities to play first against each of its opponents. The winner will be the entry that has the best win-loss record. One win (or fraction of a win) will be deducted for each second of cumulative execution time. 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.
Our experiment with new development environments has been less than successful - no entries were submitted using alternative environments for either the September and October Challenges. So this will be a native PowerPC Challenge, using the CodeWarrior Pro 7 environment. Solutions may be coded in C or C++.
Three Months Ago Winner
Congratulations to first time Challenge contestant Tony Cooper (New Zealand) for winning the August Caribbean Cruising Challenge. This problem called for contestants to sail a simulated boat around a sequence of marks, optimizing sail trim and heading to minimize the time required to complete the course. The problem was complicated by the fact that it took me several tries to debug the test code, and I appreciate the patience of the 8 people who persevered and submitted entries.
I evaluated the solutions to this Challenge using twelve scenarios, each consisting of four marks, differing in wind speed, wind direction, and wind variability. The three top-scoring entries were very close in the time required to complete the courses, although they adopted different strategies. The paths taken by the top two solutions for one test case are depicted below. The initial wind direction in the diagrams is coming down from the top of the page, so that the path from the first mark to the second begins directly upwind. Tony Cooper adjusted the boat heading more frequently, attempting to minimize the distance traveled. The second-place entry by Alan Hart, kept the boat further off the wind, traveling a greater distance at a higher speed. The third-place entry by Jonny Taylor took a path similar to Hart's, but stayed even further off the wind.
Tony's entry trims the sail based on a table lookup, which leaves him vulnerable to changes in sailing model. Other entries spent time experimenting with sail trim, making their solutions more interesting in some respects and more realistic. As it turns out, however, Tony's approach was good enough to eek out a Challenge win.
![](/file/12652/www.mactech.com.tar/www.mactech.com/articles/mactech/Vol.17/17.11/Nov01Challenge/figure01.gif)
Cooper
![](/file/12652/www.mactech.com.tar/www.mactech.com/articles/mactech/Vol.17/17.11/Nov01Challenge/figure02.gif)
Hart
David Whitney submitted two Java entries, one pure Java, and one that used Java Native Interface techniques to integrate with the C test code. Dave's entries used a version of the JDK that isn't supported under Mac OS 9. He and I worked to get his entry running under Mac OS X, but unfortunately I didn't succeed in time for publication. I may write more about using JNI in the Challenge in a later column.
The table below lists, for each of the solutions submitted, the time to complete the simulated sailing courses, the cumulative execution time, the total score (with lower scores being better), and the number of sailing marks successfully navigated. It also lists the code size, data size, and programming language of 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 | Race Time | Time(msecs) | Score |
Tony Cooper | 73749 | 731 | 74479 |
Alan Hart (25) | 74859 | 475 | 75334 |
Jonny Taylor (56) | 75780 | 1117 | 76896 |
Tom Saxton (189) | 82292 | 449 | 82740 |
Ernst Munter (778) | 207026 | 1427 | 208453 |
David Whitney | |||
K. S. | 962334 | 7465 | 963628 |
J. S. | 404200 | 8632 | 1102509 |
Name | Marks | Data Size | Code Size | Lang |
Tony Cooper | 48 | 1408 | 1100 | C |
Alan Hart | 48 | 3016 | 360 | C |
Jonny Taylor | 48 | 4716 | 636 | C |
Tom Saxton | 48 | 948 | 516 | C++ |
Ernst Munter | 48 | 1336 | 140 | C++ |
David Whitney | Java | |||
K. S. | 34 | 2476 | 521 | C |
J. S. | 9 | 9652 | 664 | C |
Top Contestants...
Listed here are the Top Contestants for the Programmer's Challenge, including everyone who has accumulated 20 or more points during the past two years. The numbers below include points awarded over the 24 most recent contests, including points earned by this month's entrants.
Rank | Name(24 mo) | Points(24 mo) | Wins | TotalPoints |
1. | Munter, Ernst | 273 | 10 | 780 |
2. | Saxton, Tom | 75 | 2 | 193 |
3. | Rieken, Willeke | 73 | 3 | 134 |
4. | Taylor, Jonathan | 63 | 2 | 63 |
5. | Wihlborg, Claes | 49 | 2 | 49 |
6. | Maurer, Sebastian | 38 | 1 | 108 |
10. | Mallett, Jeff | 20 | 1 | 114 |
11. | Truskier, Peter | 20 | 1 | 20 |
12. | Cooper, Tony | 20 | 1 | 20 |
...and the Top Contestants Looking for a Recent Win
In order to give some recognition to other participants in the Challenge, we also list the high scores for contestants who have accumulated points without taking first place in a Challenge during the past two years. Listed here are all of those contestants who have accumulated 6 or more points during the past two years.
Rank | Name | Points(24 mo) | TotalPoints |
7. | Boring, Randy | 32 | 144 |
8. | Shearer, Rob | 28 | 62 |
9. | Sadetsky, Gregory | 22 | 24 |
13. | Schotsman, Jan | 14 | 14 |
14. | Nepsund, Ronald | 10 | 57 |
15. | Hart, Alan | 10 | 35 |
16. | Day, Mark | 10 | 30 |
17. | Downs, Andrew | 10 | 12 |
18. | Desch, Noah | 10 | 10 |
19. | Duga, Brady | 10 | 10 |
20. | Fazekas, Miklos | 10 | 10 |
21. | Flowers, Sue | 10 | 10 |
22. | Nicolle, Ludovic | 7 | 55 |
23. | Hala, Ladislav | 7 | 7 |
24. | Leshner, Will | 7 | 7 |
25. | Miller, Mike | 7 | 7 |
There are three ways to earn points: (1) scoring in the top 5 of any Challenge, (2) being the first person to find a bug in a published winning solution or, (3) being the first person to suggest a Challenge that I use. The points you can win are:
1st place | 20 points | |
2nd place | 10 points | |
3rd place | 7 points | |
4th place | 4 points | |
5th place | 2 points | |
finding bug | 2 points | |
suggesting Challenge | 2 points |
Here is Tony's winning Caribbean Cruising solution:
CaribbeanCruising.c
Copyright © 2001
Tony Cooper
#include "CarribeanCruising.h" #include <stdio.h> #include <math.h> /* This is probably a dynamic programming problem but those algorithms chew up CPU time. Real sailors use heuristics. This code does too. I believe that most of the heuristics in yacht racing are to deal with wind shifts. Same here. Unfortunately all these heuristics and optimisation tables are for Bob's boat. If the real boat is disimilar then we could find ourselves in a bit of a bathtub. */ enum {kStarboardTack = -1, kNoTack = 0, kPortTack = 1}; const double PI = 3.14159265358979; const double kRadToDeg = (180.0/PI); const double kDegToRad = (PI/180.0); // these next consts can be tweaked to optimise the algorithm const double kMinTackTime = 15.0; // minimum time to maintain current tack (make this too small and you tack too // often, too large and your tacks // go wide of the mark making you vulnerable if the wind shifts const double tweakFactor = 0.0; // 0.5 is optimal - dunno why. But 0.00 is symmetrical const Boolean gUseVMC = true; // use VMC when not tacking rather than follow the rhumb line // it only helps when wind variability > 7 and it eats CPU time so setting it false may be optimal const double VMCfraction = 0.10; // fraction of the VMC course change to use (0 to 1) - the more variable the wind // the higher the optimal fraction // the next section has the optimal settings for Bob's boat // they are not consts because we may change them if we find ourselves not in Bob's // boat static Direction optimalTackAngle = 64*kDegToRad; // optimal sailtrim angles for Bob's boat at 10 knots wind and 25 knots wind static Direction optimalSailAngles10[28] = { 5,5,5,5,5,5,5,10,15,15,15,20,20,20,25,25,30,30,35,40,45,45,55, 60,65,75,80,90 }; static Direction optimalSailAngles25[28] = { 5,5,5,5,5,5,10,15,15,15,20,20,25,25,25,30,30,35,40,40,45,50,55, 60,70,75,80,90 }; // optimal boat speeds at all points of sail at 10 knots wind and 25 knots wind static double optimalSpeeds10[28] = { 1.127832,2.197660,3.230089,4.224883,5.178596,6.086716,6.797097, 7.115055,7.393258,7.580791,7.722331,7.811481,7.889993,7.905046, 7.914209,7.875377,7.821882,7.728490,7.627867,7.496973,7.355342, 7.213593,7.078046,6.952483,6.841550,6.756485,6.704573,6.688348 }; static double optimalSpeeds25[28] = { 2.735935,5.313390,7.793669,10.17909,12.462901,14.269482, 15.080794,15.786205,16.311792,16.710061,17.072551,17.343519, 17.519245,17.671387,17.693380,17.718675,17.626386,17.534003, 17.352610,17.138842,16.923432,16.679922,16.440601,16.210064, 16.010814,15.869028,15.763844,15.746795 }; static Position *gMarks; static short gNumberOfMarks; static short gCurrentMark; static double timeOnCurrentTack = 0.0; // time on current tack static int currentTack; static double prevTime = 0; static double NormalizeAngle(double angle) { while (angle>PI) angle-=2.0*PI; while (angle<=-PI) angle+=2.0*PI; return angle; } void InitCarribeanCruise( short numberOfMarks, Position mark[], /* must pass through mark[i] for each i in turn */ double tolerance, /* must pass within this distance of each mark */ double integrationInterval /* amount of time between calls to Cruise, in seconds */ ) { #pragma unused (tolerance,integrationInterval) gMarks = mark; gNumberOfMarks = numberOfMarks; gCurrentMark = 0; } Boolean /* done */ Cruise( Position boatLocation, /* boat position at the start of this time segment */ Velocity boatVelocity, /* boat velocity at the start of this time segment */ Velocity windVelocity, /* true wind velocity at this location and time */ Direction bowDirection, /* direction the bow is pointing */ short marksPickedUp, /* number of marks picked up thus far */ double currentTime, /* time since cruise start, in seconds */ Direction *targetBowDirection, /* commanded boat direction */ Direction *sailTrim /* commanded sail trim, 0..PI/4, measured as angle off the stern, in the direction away from the source of the wind. Actual sail position is a function of trim and wind direction. */ ) { #pragma unused(boatVelocity,bowDirection) double vectorToNextMarkX,vectorToNextMarkY; Direction directionOfNextMark; Direction trueHeadingOffWind, trueDirectionOffWind; Direction optimalBowDirection, optimalSailTrim; Direction optimalBowDirection1, optimalBowDirection2; Velocity trueBoatVelocity; int newTack = kNoTack; double VMC, maxVMC; Boolean canChangeTack; Boolean useVMC; int directionIndex, i; if (marksPickedUp > gCurrentMark) { gCurrentMark = marksPickedUp; currentTack = kNoTack; timeOnCurrentTack = 0.0; } canChangeTack = (currentTack == kNoTack) || (timeOnCurrentTack >= kMinTackTime); useVMC = gUseVMC; /* find direction toward current mark */ vectorToNextMarkX = gMarks[gCurrentMark].x - boatLocation.x; vectorToNextMarkY = gMarks[gCurrentMark].y - boatLocation.y; directionOfNextMark = atan2(vectorToNextMarkX,vectorToNextMarkY); // normalised windVelocity.direction = NormalizeAngle(windVelocity.direction); /* find optimal heading */ trueDirectionOffWind = NormalizeAngle(directionOfNextMark - (PI + windVelocity.direction)); if (fabs(trueDirectionOffWind) < optimalTackAngle) { // we cannot sail into the wind so have to tack // when we tack there are two directions we can tack in if (!canChangeTack) { optimalBowDirection = PI + windVelocity.direction + currentTack*optimalTackAngle; // we are not allowed to change tack newTack = currentTack; } else { optimalBowDirection1 = PI + windVelocity.direction + optimalTackAngle; // port tack optimalBowDirection2 = PI + windVelocity.direction - optimalTackAngle; // starboard tack // of the two possible tacks choose the one closest to the direction the mark // is in this keeps you closer to the mark which makes you less vulnerable if // the wind changes if (fabs(NormalizeAngle(optimalBowDirection1 - directionOfNextMark)) / fabs(NormalizeAngle(optimalBowDirection2 - directionOfNextMark)) < 1-tweakFactor) { //if (fabs(NormalizeAngle(optimalBowDirection1 - directionOfNextMark)) < // fabs(NormalizeAngle(optimalBowDirection2 - directionOfNextMark))) { optimalBowDirection = optimalBowDirection1; newTack = kPortTack; } else { optimalBowDirection = optimalBowDirection2; newTack = kStarboardTack; } } } else { newTack = kNoTack; if (useVMC) { /* calculate the direction of the 28 that gives us the best VMC (velocity made in the direction of the course) this may be a better line that the rhumb line because it can leave us closer to the mark if the wind shifts */ directionIndex = -1; maxVMC = 0.0; for (i = 0; i < 28; i++) { // VMC is the component of the boatspeed in the direction of the mark // VMC is the speed times the cos of the angle between the boat direction // and the mark if (trueDirectionOffWind > 0) trueBoatVelocity.direction = NormalizeAngle(PI + windVelocity.direction + (45 + i * 5)*kDegToRad); else trueBoatVelocity.direction = NormalizeAngle(PI + windVelocity.direction - (45 + i * 5)*kDegToRad); if (windVelocity.speed > 17.5) trueBoatVelocity.speed = optimalSpeeds25[i]; else trueBoatVelocity.speed = optimalSpeeds10[i]; VMC = trueBoatVelocity.speed * cos(trueBoatVelocity.direction - directionOfNextMark); // look at VMC for the port tack if (VMC > maxVMC) { maxVMC = VMC; directionIndex = i; optimalBowDirection = trueBoatVelocity.direction; } } if (directionIndex != -1) { // positive VMC found // we now have two directions to choose: optimalBowDirection and // directionOfNextMark // we now compromise between them /*if (fabs((optimalBowDirection - directionOfNextMark)*kRadToDeg) > 40) { FILE *outFile; outFile = fopen("Carribean Cruising-output","a"); fprintf(outFile,"%f %f %f %f\n", trueDirectionOffWind*kRadToDeg, directionOfNextMark*kRadToDeg, optimalBowDirection*kRadToDeg, cos(optimalBowDirection - directionOfNextMark)); fclose(outFile);} */ optimalBowDirection = directionOfNextMark + (optimalBowDirection - directionOfNextMark) * VMCfraction; } else { optimalBowDirection = directionOfNextMark; } } else { optimalBowDirection = directionOfNextMark; } } /* find optimal sail trim */ trueHeadingOffWind = fabs(NormalizeAngle(PI + windVelocity.direction - optimalBowDirection)); directionIndex = (int)((trueHeadingOffWind*kRadToDeg + 2.5 - 45)/5.0); // 2.5 is for rounding to nearest, 2.5, 45, and 5.0 are degrees hence kRadToDeg if (directionIndex < 0) directionIndex = 0; // not necessary but just in case if (directionIndex > 27) directionIndex = 27; // not necessary but just in case if (windVelocity.speed > 17.5) optimalSailTrim = optimalSailAngles25[directionIndex]*kDegToRad; else optimalSailTrim = optimalSailAngles10[directionIndex]*kDegToRad; *targetBowDirection = optimalBowDirection; *sailTrim = optimalSailTrim; if (currentTack == newTack) timeOnCurrentTack += currentTime - prevTime; else { currentTack = newTack; timeOnCurrentTack = 0; } prevTime = currentTime; return false; } void TermCarribeanCruise(void) {}
![](/file/12652/www.mactech.com.tar/www.mactech.com/sites/all/themes/custom_front/img/search_text.gif)
- SPREAD THE WORD:
- Slashdot
- Digg
- Del.icio.us
- Newsvine