Jun 01 Programmers Challenge

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

by Bob Boonstra, Westford, MA

Dots

You have probably played the game Dots before, although perhaps not in quite some time. My memory of the game dates back to childhood, when we played it in the car while on some long trip. Greg Sadetsky suggested that Dots might make an interesting Challenge, and he wins two Challenge points for that suggestion.

The game starts with a piece of paper with a rectangular grid of NxN dots. The game proceeds with two players alternating turns connecting adjacent dots with a line. Two dots are adjacent if they are in the same row and in adjacent columns, or in the same column and in adjacent rows. The object of the game is to take possession of more squares than does your opponent. Each time a player connects dots that form the fourth edge of a square, the player takes possession of that square. A line can complete zero, one, or two squares. When a player completes one or more squares, s/he is entitled to make another move, and to continue making additional moves as long as a square is completed with each move. The game continues until every square has been formed.

The prototype for the code you should write is:

```typedef struct Dot {
short row;      /* row number of dot, 0..boardSize-1 */
short col;      /* column number of dot, 0..boardSize-1 */
} Dot;

typedef struct DotLine {
Dot dot1;      /* first dot of a line */
Dot dot2;      /* second dot of a line */
/*   legal lines are formed by dots in the same row, in adjacent columns, or in the same column
} DotLine;

void InitDots(
short boardSize,      /* number of dots per row/col in board */
Boolean playFirst,    /* true if you play first, false of opponent plays first */
WindowPtr dotWindow   /* color window where you should draw game results */
);

void OpponentMove(
const DotLine opponentLine   /* line formed by your opponent on previous move */
);

short /* number of lines generated   */ PlayDots(
DotLine yourLines[]         /* return the lines you form here */
);

void TermDots(void);      /* return any storage you allocated */
```

Play begins with a call to your InitDots routine, where you are given the size of the game board (boardSize), an indicator of who plays first (playFirst), and a pointer to a CWindow (passed as a WindowPtr because that’s what most toolbox routines expect). In that window, you will be required to display the progress of the game as it proceeds.

When it is your turn to move, your PlayDots routine will be called. Your code should select the most advantageous move and return it in yourLines[0]. If that move forms a square, you can select an additional move, store it in yourLines[1], and continue as long as squares are formed. PlayDots should return the number of moves you made during your turn.

After your opponent has played, your OpponentMove routine will be called one or more times, once for each move made by your opponent. The move will be provided in the opponentLine parameter, for use in display and in updating your data structures.

After each of your moves, and after notification of each opponent move, you should display the move and the updated game state in the dotWindow. The window should also display the number of squares completed by each player. The details of the display are left to you, as long as the display is correct.

When all of the squares have been formed, your TermDots routine will be called. You should deallocate any dynamically allocated memory and perform any other cleanup required.

The winner will be determined by a round-robin or other fair tournament played with multiple board sizes. Scoring is based on minimizing your point total, calculated as the number of squares that your opponent occupies, plus a penalty of 1% for each millisecond your solution takes to execute.

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, C++, or Pascal.

Three Months Ago Winner

Congratulations to Claes Wihlborg for winning the March DragSort Challenge. The object of this Challenge was to sort a list by dragging items from one position to another, minimizing the cumulative distance that the drag cursor traveled while moving to pick up an item and while dragging it to its new position. Four of the five entries I received sorted my test cases correctly, and three of the four used the same basic algorithm. Claes’ entry, however, did so much more efficiently than the others, earning him the Challenge win.

The winning solution moves down the list and picks up the first out-of-order item, dragging it in the same direction and dropping it before the next in-order item. It then continues scanning the list in the same direction, picking up the next out-of-order item and dropping it were it belongs. When it reaches the end of the list, it reverses direction and does the same thing moving backward. It continues to move up and down the list until all of the items are in the correct order. A straightforward and efficient solution.

I evaluated the entries using six test cases using lists ranging up to 6500 elements. Since the problem was based on a hypothetical Usenet application, most of the test cases were based on lists that were ordered correctly except for some relatively small percentage of the list items.

As the best-placing entry from someone who has not won a Challenge in the past two years, Randy Boring 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 penalty points earned by each entry, the total time in milliseconds, and the number of select and drag position moves used to sort the test cases. 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(msecs) Moves Claes Wihlborg (29) 29026776 180 29026284 Ernst Munter (721) 29026987 706 29026284 Randy Boring (135) 29027737 1456 29026284 Marco Aiello 84384025 4600 84379428 R. O. Incorrect N/A
 Name Code Size Data Size Lang Claes Wihlborg 704 8 C++ Ernst Munter 2380 80 C++ Randy Boring 2212 145 C++ Marco Aiello 1416 28 C++ R. O. 43432 6120 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 Wins(24 mo) Total Points(24 mo) 1. Munter, Ernst 294 11 731 2. Rieken, Willeke 87 3 134 3. Saxton, Tom 76 2 185 4. Maurer, Sebastian 68 2 108 5. Taylor, Jonathan 56 2 56 6. Shearer, Rob 55 1 62 7. Wihlborg, Claes 49 2 49

... 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) Total Points 8. Boring, Randy 39 142 9. Jones, Dennis 12 22 10. Sadetsky, Gregory 12 14 11. Downs, Andrew 12 12 12. Day, Mark 10 30 13. Duga, Brady 10 10 14. Fazekas, Miklos 10 10 15. Flowers, Sue 10 10 16. Strout, Joe 10 10 17. Nicolle, Ludovic 7 55 18. Hala, Ladislav 7 7 19. Miller, Mike 7 7 20. Schotsman, Jan 7 7 21. Widyatama, Yudhi 7 7 22. 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 Claes’ winning DragSort solution:

DragSort.cp
Claes Wihlborg

```/*
The program takes a very simple approach and implements
bubblesort with alternating sort directions.
*/

#include “DragSort.h”

//—————————————————————————————————- DragSort

long /* numMoves */ DragSort(
long itemsToSort[],   /* array of items to be sorted */
long numItemsToSort,  /* number of itemsToSort */
long startPosition,   /* item initially selected */
Move sortMoves[]      /* store Moves that sort the array here */
)
{
Move *nextMove = sortMoves;

long temp, temp2;

long *p, *oldp, *pMin, *pMax, *newMin, *newMax;

pMin = itemsToSort;
pMax = itemsToSort + numItemsToSort - 1;

// If strartpos <> 0, sweep down

p = itemsToSort + startPosition;
while( p > pMin )
{
oldp = p—;

if( (temp = *oldp) < *p )
{
nextMove->selectPosition = oldp - itemsToSort;
do
{
*oldp = *p;
oldp = p—;
}
while( (p >= pMin) && (temp < *p ) );
nextMove++->dragToPosition =  oldp - itemsToSort;
*oldp = temp;
}
}

// 1:st iteration: sweep once up and once down.
// this iteration puts at least the smallest and the biggest items in place.

newMax = 0;
newMin = 0;

p = pMin;
while( p < pMax ) //sweep up
{
oldp = p++;

if( (temp = *oldp) > (temp2 = *p) )
{
nextMove->selectPosition = oldp - itemsToSort;
do
{
*oldp = temp2;
oldp = p++;
}
while( (p <= pMax) && (temp > (temp2 = *p)) );
nextMove++->dragToPosition =  oldp - itemsToSort;
*oldp = temp;
newMax = oldp;
}
}

if( !newMax ) return nextMove - sortMoves;
// no more items in wrong order

pMax = newMax - 1;
p = pMax;
while( p > pMin ) //sweep down
{
oldp = p—;

if( (temp = *oldp) < (temp2 = *p) )
{
nextMove->selectPosition = oldp - itemsToSort;
do
{
*oldp = temp2;
oldp = p—;
}
while( (p >= pMin) && (temp < (temp2 = *p)) );
nextMove++->dragToPosition =  oldp - itemsToSort;
*oldp = temp;
newMin = oldp;
}
}

if( !newMin ) return nextMove - sortMoves;
// no more items in wrong order
pMin = newMin + 1;

do //main loop: sweep once up and once down for every iteration
{
newMax = 0;
newMin = 0;

p = pMin;

while( p < pMax ) //sweep up
{
oldp = p++;

if( (temp = *oldp) > (temp2 = *p) )
{
nextMove->selectPosition = oldp - itemsToSort;
do
{
*oldp = temp2;
oldp = p++;
}
while( temp > (temp2 = *p) );
//simpler condition as biggest element in correct place
nextMove++->dragToPosition =  oldp -  itemsToSort;
*oldp = temp;
newMax = oldp;
}
}

if( !newMax ) break;  // no more items in wrong order

pMax = newMax - 1;
p = pMax;

while( p > pMin ) //sweep down
{
oldp = p—;

if( (temp = *oldp) < (temp2 = *p) )
{
nextMove->selectPosition = oldp - itemsToSort;
do
{
*oldp = temp2;
oldp = p—;
}
while( temp < (temp2 = *p) );
//simpler condition as smallest element in correct place
nextMove++->dragToPosition =  oldp - itemsToSort;
*oldp = temp;
newMin = oldp;
}
}

pMin = newMin + 1;
}
while( newMin );

return nextMove - sortMoves;
}
```

Community Search:
MacTech Search:

Parallels Desktop 10.2.0 - Run Windows a...
Parallels Desktop is simply the world's bestselling, top-rated, and most trusted solution for running Windows applications on your Mac. With Parallels Desktop for Mac, you can seamlessly run both... Read more
LaunchBar 6.2 - Powerful file/URL/email...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Firefox 37.0 - Fast, safe Web browser. (...
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
Arq 4.11 - Online backup to Google Drive...
Arq is super-easy online backup for the Mac. Back up to your own Google Drive storage (15GB free storage), your own Amazon Glacier (\$.01/GB per month storage) or S3, or any SFTP server. Arq backs up... Read more
MacFamilyTree 7.3.4 - Create and explore...
MacFamilyTree gives genealogy a facelift: it's modern, interactive, incredibly fast, and easy to use. We're convinced that generations of chroniclers would have loved to trade in their genealogy... Read more
Yummy FTP 1.10.2 - FTP/SFTP/FTPS client...
Yummy FTP is an FTP + SFTP + FTPS file transfer client which focuses on speed, reliability and productivity. Whether you need to transfer a few files or a few thousand, schedule automatic backups, or... Read more
VueScan 9.5.08 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Iridient Developer 3.0.1 - Powerful imag...
Iridient Developer (was RAW Developer) is a powerful image conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more
Monodraw 0.8.4.1 - Powerful ASCII art ed...
Monodraw allows you to easily create text-based art (like diagrams, layouts, flow charts) and visually represent algorithms, data structures, binary formats and more. Because it's all just text, it... Read more
Air Video Server HD 2.1.0 - Stream video...
Air Video Server HD streams videos instantly from your computer on your iPhone, iPad, iPod touch or Apple TV. No need to worry about converting or transferring files. We took everything that was... Read more

Latest Forum Discussions

Marvel Mighty Heroes, the Ultimate Marve...
DeNA and Marvel Entertainment have brought us a new action-packed brawler: Marvel Mighty Heroes. You can play with up to four of your friends as you favorite marvel heroes like Iron Man, Thor, Spider-Man, Captain America, Star-Lord, Hulk, and... | Read more »
Take Note - The Jot Script 2 Evernote Ed...
Adonit's Jot Script 2 sylus has an all-new edition that's meant to be Evernote's BFF. The sylus has been redesigned to work better with iPads and give you faster stroke tracking, smoother line rendering, and better tip-to-line accuracy. | Read more »
INFINIT Lets Mobile Users Send Files of...
Infinit  is a file sharing app that ignores file size limits. It maintains the original quality of your photos and videos so you can be sure they look awesome after sending. You can move entire albums of photos or full HD films from your iPhone to... | Read more »
Serious Sam Double D Developer is Making...
There's nothing like the thrill of watching a horse race, especially when the horses are drunk.  | Read more »
2K Announces WWE 2K, Mobile's First...
It seems like this month has been pretty big for wrestling. First Wrestlemania, then 2K has announces that they're releasing  WWE 2K for iOS. It's a simulation-based WWE game where you'll get to play with several WWE superstars such as John Cena, ... | Read more »
How the Apple Watch Could Change the Fac...
The Apple Watch is still a ways out, but my previous musings on the wearable’s various features got me thinking: what might it be like a year after launch? Two years? Five years? What if it becomes a symbiotic part of the iOS framework to the point... | Read more »
You Can Start Challenging Your Friends t...
Last year we reported that Sebastian Gosztyla's new game, Dual, was theorized to be released sometime during the summer of 2014. Sadly that did not become a reality, but the good news it there is now an official release date. | Read more »
Forgotten Memories : Alternate Realities...
Forgotten Memories : Alternate Realities, from Psychoz Interactive, is planned for release on April 23. The Resident Evil, Silent Hill, and Alone in the Dark inspired horror game puts you in the shoes of Rose Hawkins as she searches for a missing... | Read more »
Pie In The Sky: A Pizza Odyssey (Games)
Pie In The Sky: A Pizza Odyssey 1.0 Device: iOS Universal Category: Games Price: \$2.99, Version: 1.0 (iTunes) Description: A game about delivering pizza. In space. | Read more »
Chosen Gives Hopeful Singers, Songwriter...
If YouTube videos and reality TV shows like The Voice have taught us one thing, it’s that there are a lot of people out there who are anxious to show the world their talents. And if they’ve taught us a second thing, it’s that there’s an almost... | Read more »

Price Scanner via MacPrices.net

Will Microsoft’s Surface 3 Give The 12-inch M...
The more I ruminate over the new 12-inch MacBook, the more it occurs that it’s probably going to be more of a cannibalization threat to high-end iPads (including a new 12-inch ‘Pad when/if that... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
MacMall has the 2013 13″ 2.4GHz/128GB Retina MacBook Pro available for \$949.99 for a limited time. Shipping is free. Their price is \$350 off original MSRP, and it’s the only sub-\$1000 new Retina... Read more
Adobe today announced the availability of Adobe Comp CC, a free iPad app that enables rapid creation of layout concepts for mobile, Web and print projects. With Comp CC, designers can rough out and... Read more
13-inch 2.6GHz/256GB Retina MacBook Pro avail...
Best Buy has clearance 2014 13″ 2.6GHz/256GB Retina MacBook Pros available for \$1199.99 including free shipping. Their price is \$300 off original MSRP, and it’s the lowest price for this model.... Read more
Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
21-inch 1.4GHz iMac on sale for \$999, save \$1...
Best Buy has the 21″ 1.4GHz iMac on sale for \$999.99 on their online store. Choose free shipping or free local store pick up. Price is for online orders only, in-store prices may vary. Their price is... Read more
2.6GHz Mac mini on sale for \$649, save \$50
Amazon has the 2.6GHz Mac mini on sale for \$649.99 including free shipping. Their price is \$50 off MSRP, and it’s the lowest price available for this model. Read more
Textkraft Professional 3.2 Powerful iPad Text...
Finally it’s springtime, at least theoretically in my neck of the woods, where we’re still navigating canyons between towering snowbanks with temperatures well below freezing in winter weather that... Read more
Apple offering refurbished 27-inch 5K iMacs f...
The Apple Store is offering Apple Certified Refurbished 27″ 3.5GHz 5K iMacs for \$2119 including free shipping. Their price is \$380 off the price of new models, and it’s the lowest price available for... Read more
16GB iPad mini on sale for \$199, save \$50
Walmart has 16GB iPad minis (1st generation) available for \$199.99 on their online store, including free shipping. Their price is \$50 off MSRP. Online orders only. Read more

Jobs Board

DevOps Software Engineer - *Apple* Pay, iOS...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring 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
Sr. Technical Services Consultant, *Apple*...
**Job Summary** Apple Professional Services (APS) has an opening for a senior technical position that contributes to Apple 's efforts for strategic and transactional Read more
Lead *Apple* Solutions Consultant - Retail...
**Job Summary** Job Summary The Lead ASC is an Apple employee who serves as the Apple business manager and influencer in a hyper-business critical Reseller's store Read more
*Apple* Pay - Site Reliability Engineer - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more