Nov 01 Challenge

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.

Cooper

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
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;

// 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

// 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 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);

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 *
else
trueBoatVelocity.direction = NormalizeAngle(PI +
windVelocity.direction - (45 + i *
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",
cos(optimalBowDirection - directionOfNextMark));
fclose(outFile);}
*/

optimalBowDirection = directionOfNextMark +
(optimalBowDirection - directionOfNextMark) *
VMCfraction;
} else {
optimalBowDirection = directionOfNextMark;
}
} else {
optimalBowDirection = directionOfNextMark;
}
}

/* find optimal sail trim */

windVelocity.direction - optimalBowDirection));
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 =
else
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:

## Latest Forum Discussions

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

## Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for \$500-\$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for \$699, \$300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to \$600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at \$2969 and ranging up to \$600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to \$480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at \$1699 and ranging up to \$480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for \$80-\$100 off MSRP, starting only \$249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a \$50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for \$249, Certified Refurbished. That’s \$50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to \$400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for \$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for \$150-\$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering \$170-\$200 discounts on new...
Amazon is offering a \$170-\$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at \$1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

## Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more