TweetFollow Us on Twitter

Nov 01 Challenge

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

by Bob Boonstra, Westford, MA


While rummaging through a dresser drawer, I ran across a collection of magnetic board games put out by a company called Midnite Snack, 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.



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:

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] = {
static Direction optimalSailAngles25[28] = {

// optimal boat speeds at all points of sail at 10 knots wind and 25 knots wind
static double optimalSpeeds10[28] = {
static double optimalSpeeds25[28] = {

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 = 
   /* 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 + 
// 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 *
               trueBoatVelocity.direction = NormalizeAngle(PI + 
                     windVelocity.direction - (45 + i *
            if (windVelocity.speed > 17.5)
               trueBoatVelocity.speed = optimalSpeeds25[i];
               trueBoatVelocity.speed = optimalSpeeds10[i];
            VMC = trueBoatVelocity.speed * 
                     cos(trueBoatVelocity.direction -
            // 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",
            directionOfNextMark*kRadToDeg, optimalBowDirection*kRadToDeg,
            cos(optimalBowDirection - directionOfNextMark));

            optimalBowDirection = directionOfNextMark + 
               (optimalBowDirection - directionOfNextMark) * 
         } else {
            optimalBowDirection = directionOfNextMark;
      } else {
         optimalBowDirection = directionOfNextMark;
   /* find optimal sail trim */

   trueHeadingOffWind = fabs(NormalizeAngle(PI + 
               windVelocity.direction - optimalBowDirection));
   directionIndex = (int)((trueHeadingOffWind*kRadToDeg + 2.5 - 
      // 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 = 
      optimalSailTrim = 

   *targetBowDirection = optimalBowDirection;
   *sailTrim = optimalSailTrim;

   if (currentTack == newTack)
      timeOnCurrentTack += currentTime - prevTime;
   else {
      currentTack = newTack;
      timeOnCurrentTack = 0;
   prevTime = currentTime;

   return false;

void TermCarribeanCruise(void) {}


Community Search:
MacTech Search:

Software Updates via MacUpdate

Gopogo guide - How to bounce like the be...
Nitrome just launched a new game and, as to be expected, it's a lot of addictive fun. It's called Gopogo, and it challenges you to hoparound a bunch of platforms, avoiding enemies and picking up shiny stuff. It's not easy though - just like the... | Read more »
Sago Mini Superhero (Education)
Sago Mini Superhero 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: KAPOW! Jack the rabbit bursts into the sky as the Sago Mini Superhero! Fly with Jack as he lifts impossible weights,... | Read more »
Star Wars: Galaxy of Heroes guide - How...
Star Wars: Galaxy of Heroes is all about collecting heroes, powering them up, and using them together to defeat your foes. It's pretty straightforward stuff for the most part, but increasing your characters' stats can be a bit confusing because it... | Read more »
The best cooking apps (just in time for...
It’s that time of year again, where you’ll be gathering around the dinner table with your family and a huge feast in front of you. [Read more] | Read more »
Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »
Snowboard Party 2 (Games)
Snowboard Party 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Crowned the best snowboarding game available on the market, Snowboard Party is back to fulfill all your adrenaline needs in... | Read more »
One Button Travel (Games)
One Button Travel 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: “To cut a long story short, If you like interactive fiction, just go buy this one.” - “Oozes the polish that... | Read more »
Light Apprentice Volume 1 (Games)
Light Apprentice Volume 1 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Light Apprentice Volume 1 includes Chapters 1 to 4, all gathered in a new exclusive game. When life in the world of... | Read more »
The best games like Animal Crossing on m...
Animal Crossing amiibo Festival is out right now for the Wii U, reminding us of just how much fun that world can be. Or at least to go back and check in on our villages once in a while. [Read more] | Read more »
Between 2 Taps - Tap for Tap interview M...
Hello, and welcome back to Between 2 Taps, Tap for Tap’s Indie Dev interview series. [Read more] | Read more »

Price Scanner via

Black Friday deals on the Apple Watch and App...
Apple resellers are offering discounts and bundles with the purchase of an Apple Watch this Black Friday weekend. Below is a roundup of the deals being offered by authorized Watch resellers: Apple... Read more
Early Black Friday sale at B&H Photo, up...
B&H Photo has all new Macs on sale for up to $500 off MSRP as part of their early Black Friday sale including free shipping plus NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699 $300 off... Read more
NewerTech/OWC/MacSales Black Friday Deals 201... • Free Shipping available on nearly EVERYTHING on orders $35.00 & up within USA + • International Delivery Specials from $2.99+ Special Purolator... Read more
Walmart Black Friday deals: $100 off select i...
Walmart has released their Black Friday deals for 2015, now available online. Choose free shipping or free local store pickup (if available): - 16GB iPad Air 2: $399, $100 off MSRP - 16GB iPad Air: $... Read more
Photo Cleaner 1.0 Reclaims iPhone Storage Spa...
Seoul, Korea based mix1009 has announced the release and immediate availability of Photo Cleaner 1.0, their handy iPhone app that deletes the video portion of Live Photos, in order to reclaim space... Read more
Black Friday and Holiday sales on our price t...
Scan our Mac Price Trackers for the latest Black Friday and Holiday season information on sales, bundles, and availability on systems from Apple’s authorized internet/catalog resellers. We update the... Read more
Best Buy Black Friday deals: Up to $200 off M...
Best Buy has posted their Black Friday sale prices for 2015. Save on MacBook Pros, MacBooks, MacBook Airs, iMacs, iPads, and Apple Watches. Choose free shipping or free local store pickup (if... Read more
Save $30-$40 on new Apple TVs after rebate
Adorama has new Apple TVs on sale for up to $40 off MSRP after mail-in rebate, good through December 15th. Shipping is free, and Adorama charges NY & NJ sales tax only: - 32GB Apple TV: $119.99... Read more
13-Inch Haswell MacBook Air At Two Years – Th...
The 13-inch mid-2013 “Haswell” MacBook Air I ordered in Apple’s November 2013 Black Friday sale was my first new Mac in four and a half years — the longest interval I’ve gone between system upgrades... Read more
Target Black Friday Early Access deals: $100...
Target is offering early access to their Black Friday deals on Apple products on their online store for today, the 25th, only. Choose free shipping or free local store pickup (if available): - Apple... Read more

Jobs Board

*Apple* Enterprise / Government Professional...
# Apple Enterprise / Gove ment Professional Services Engineer Job Number: 42292976 Reston, Virginia, United States Posted: Aug. 18, 2015 Weekly Hours: 40.00 **Job Read more
iOS Wallet & *Apple* Pay Engineer - App...
# iOS Wallet & Apple Pay Engineer Job Number: 40586801 Santa Clara Valley, Califo ia, United States Posted: Nov. 16, 2015 Weekly Hours: 40.00 **Job Summary** The iOS Read more
Software Engineer, *Apple* Watch - Clock Fa...
# Software Engineer, Apple Watch - Clock Face Team Job Number: 44368761 Santa Clara Valley, Califo ia, United States Posted: Nov. 14, 2015 Weekly Hours: 40.00 **Job Read more
Administrative Assistant, *Apple* Online St...
# Administrative Assistant, Apple Online Store Job Number: 43992352 Santa Clara Valley, Califo ia, United States Posted: Nov. 9, 2015 Weekly Hours: 40.00 **Job Summary** Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.