TweetFollow Us on Twitter

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 
   in adjacent rows */
} 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
Copyright © 2001
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;
}
 
AAPL
$98.15
Apple Inc.
-0.23
MSFT
$43.58
Microsoft Corpora
-0.31
GOOG
$587.42
Google Inc.
+1.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

Knock 1.1.7 - Unlock your Mac by knockin...
Knock is a faster, safer way to sign in. You keep your iPhone with you all the time. Now you can use it as a password. You never have to open the app -- just knock on your phone twice, even when it's... Read more
Mellel 3.3.6 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
LibreOffice 4.3.0.4 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
Freeway Pro 7.0 - Drag-and-drop Web desi...
Freeway Pro lets you build websites with speed and precision... without writing a line of code! With it's user-oriented drag-and-drop interface, Freeway Pro helps you piece together the website of... Read more
Drive Genius 3.2.4 - Powerful system uti...
Drive Genius is an OS X utility designed to provide unsurpassed storage management. Featuring an easy-to-use interface, Drive Genius is packed with powerful tools such as a drive optimizer, a... Read more
Vitamin-R 2.15 - Personal productivity t...
Vitamin-R creates the optimal conditions for your brain to work at its best by structuring your work into short bursts of distraction-free, highly focused activity alternating with opportunities for... Read more
Toast Titanium 12.0 - The ultimate media...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more
OS X Yosemite Wallpaper 1.0 - Desktop im...
OS X Yosemite Wallpaper is the gorgeous new background image for Apple's upcoming OS X 10.10 Yosemite. This wallpaper is available for all screen resolutions with a source file that measures 5,418... Read more
Acorn 4.4 - Bitmap image editor. (Demo)
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
Bartender 1.2.20 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more

Latest Forum Discussions

See All

Ice Wings Plus (Games)
Ice Wings Plus 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: THE GREAT ENDLESS RUNNER OF COMBAT JETS IS BACK !! With more than 680.000 downloads in the App Store, Ice Wings: Skies of Steel... | Read more »
Murl the Squirrel (Games)
Murl the Squirrel 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Meet Murl. He is teased by a group of flying squirrels because he can't fly. Determined to show them he's can fly, he meets... | Read more »
Celleste (Games)
Celleste 0.1 Device: iOS Universal Category: Games Price: $2.99, Version: 0.1 (iTunes) Description: Lots of cute action with amazing 3D graphics and a new type of gameplay! Take control over the forces of the universe to help a group... | Read more »
Super Heavy Sword (Games)
Super Heavy Sword 0.0.1 Device: iOS Universal Category: Games Price: $.99, Version: 0.0.1 (iTunes) Description: Get Ready to Get HEAVY! Monster Robot Studios presents SUPER Heavy Sword! The sequel to the smash hit HEAVY sword which... | Read more »
Angels In The Sky (Games)
Angels In The Sky 1.00 Device: iOS Universal Category: Games Price: $6.99, Version: 1.00 (iTunes) Description: - A.I.S will only run smoothly on iPhone 5s. It's NOT compatible with iPad, iPhone 5 or earlier devices.- In order to... | Read more »
80 Days (Games)
80 Days 1.0.2 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.2 (iTunes) Description: 1872, with a steampunk twist. Phileas Fogg has wagered he can circumnavigate the world in just eighty days. Choose your own route... | Read more »
Micromon (Games)
Micromon 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: 130+ Animated Monsters to Catch & Battle! No waiting, play at your own pace! Embark on an epic monster capture RPG like none... | Read more »
Empire Manager (Games)
Empire Manager 1.0 Device: iOS iPhone Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: Become ruler of an empire. Manage your economy, develop technology, hire an army and conquer the world in this addictive turn-... | Read more »
Empire Manager HD (Games)
Empire Manager HD 1.0 Device: iOS Universal Category: Games Price: $7.99, Version: 1.0 (iTunes) Description: Become ruler of an empire. Manage your economy, develop technology, hire an army and conquer the world in this addictive... | Read more »
Star Admiral Review
Star Admiral Review By Rob Thomas on July 30th, 2014 Our Rating: :: ADMIRABLE ADMIRALSUniversal App - Designed for iPhone and iPad While this new digital CCG may feel a bit familiar, Star Admiral offers a sci-fi twist and galaxy’s... | Read more »

Price Scanner via MacPrices.net

iPad Cannibalization Threat “Overblown”
Seeking Alpha’s Kevin Greenhalgh observes that while many commentators think Apple’s forthcoming 5.5-inch panel iPhone 6 will cannibalize iPad sales, in his estimation, these concerns are being... Read more
Primate Labs Releases July 2014 MacBook Pro P...
Primate Labs’ John Poole has posted Geekbench 3 results for most of the new MacBook Pro models that Apple released on Tuesday. Poole observes that overall performance improvements for the new MacBook... Read more
Apple Re-Releases Bugfixed MacBook Air EFI Fi...
Apple has posted a bugfixed version EFI Firmware Update 2.9 a for MacBook Air (Mid 2011) models. The update addresses an issue where systems may take longer to wake from sleep than expected, and... Read more
Save $50 on the 2.5GHz Mac mini, plus free sh...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $140 on an iPad Air with Apple ref...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
$250 price drop on leftover 15-inch Retina Ma...
B&H Photo has dropped prices on 2013 15″ Retina MacBook Pros by $250 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.3GHz Retina MacBook Pro: $2249, $250 off... Read more
More iPad Upgrade Musings – The ‘Book Mystiqu...
Much discussed recently, what with Apple reporting iPad sales shrinkage over two consecutive quarters, is that it had apparently been widely assumed that tablet users would follow a two-year hardware... Read more
13-inch 2.5GHz MacBook Pro on sale for $999,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $999.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $100 off MSRP. Price is... Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
WaterField Unveils 15″ Outback Solo & 13″...
Hard on the heels of Apple’s refreshed MacBook Pro Retina laptops announcement, WaterField Designs has unveiled a 15-inch version of the waxed-canvas and leather Outback Solo and a 13-inch version of... Read more

Jobs Board

Sr. Product Leader, *Apple* Store Apps - 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
Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Sr. Product Leader, *Apple* Store Apps - 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.