TweetFollow Us on Twitter

Feb 93 Challenge
Volume Number:9
Issue Number:2
Column Tag:Programmers' Challenge

Programmers' Challenge

By Mike Scanlin, MacTech Magazine Regular Contributing Author

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Surely one of the most interesting things about life is that it’s unpredictable. You’re never quite sure exactly what is going to happen next. Think about the possibilities: Without any warning whatsoever you could meet someone you haven’t seen for years, a meteor could slam into the side of your house, Elvis could reappear, or the MacTech Magazaine Programmers’ Challenge deadline could be moved up after it had been published. Just knowing that these types of things could happen certainly does keep one on one’s toes, no?

Surprise! Due to gremlins in the production room, the deadline for the Nov/Dec puzzle was stated as being Jan 1st instead of the correct date of Dec 1st. Our apologies. To be fair, we will honor all submissions received up until Jan 1st and if a better one than the winner given below comes in we will publish the new winner next month. Hopefully the gremlin traps we’ve set will prevent this from happening again. Or, since this is the second time this has happened, maybe this month’s Challenge should be to accurately guess its deadline date...

The if-nothing-better-comes-in-before-Jan-1st winner of the “Millions of Colors?” challenge is Tom Pinkerton (Wilmette, IL). While I applaud his use of a minimal initialization loop and hard-coded array indexes, there is one thing that could be improved. This loop:

 register long*  sInitPtr;
 register long i;

 sInitPtr = sBluListPtr;
 i = 64;
 while (i--) {
 sInitPtr[3] =
 sInitPtr[2] =
 sInitPtr[1] =
 sInitPtr[0] = -1;
 sInitPtr += 4;
 }

could be better written as:

 register long*  sInitPtr;
 register long i, minusOne;

 sInitPtr = sBluListPtr;
 minusOne = -1;
 i = 64*4;
 do {
 *sInitPtr++ = minusOne;
 } while (--i);

which executes faster and is fewer bytes. Other than that little nit, Tom’s solution is clever and well implemented.

New E-Mail Addresses!

In the quest for better ways to work the Programmers’ Challenge, we have added a series of e-mail addresses for the puzzle. Please use these addresses. AppleLink: MT.PROGCHAL, Internet: progchallenge@xplain.com, and CompuServe: 71552,174.

Remember, that you cannot send files over Internet, but you can just send a message with the code in the message.

Insane Anglo Warlord

Did anyone see Sneakers? The movie itself had extremely few redeeming qualities but there was an interesting effect that they did with the credits. The movie was about secret codes. Each person’s name that came up had the letters scrambled to make valid English words which would then descramble themselves to be the person’s name (without adding or deleting any letters). For instance, Robert Redford initially came up as Fort Red Border and then descrambled to Robert Redford through a series of letter rearrangement steps.

What I’d like to do is ask you to write the routine that would come up with Fort Red Border (or any other valid set of English words) when given Robert Redford as input. But that would require the use of a large word list that I’m almost positive Neil wouldn’t want to print in this tiny little column. So, instead, I’m going to ask for a subset of this effect. Given the starting string, the ending string and the desired number of steps, the challenge is to come up with the intermediate strings in an appropriately interesting way (which may or may not involve some randomness-your decision).

The prototype of the function you write is:

void Descramble(startString, endString, numSteps, 
 stepStringPtrs)
Str255  startString, endString;
unsigned short   numSteps;
Str255  *stepStringPtrs[20];

Example:

 Input:
 startString = “\pFORT RED BORDER”
 endString = “\pROBERT REDFORD ” <note space at end>
 numSteps = 4
 stepStringPtrs = <numSteps pointers to Str255s allocated
 by the caller>

 Output:
 *stepStringPtrs[0] = “\pROOR TED BFRDER”
 *stepStringPtrs[1] = “\pRORRET D BFODER”
 *stepStringPtrs[2] = “\pROBDET R RFORED”
 *stepStringPtrs[3] = “\pROBEDT RERFORD ”

You can assume the input and output strings each have the same number of uppercase letters, which is at least twice numSteps (i.e. the minimum string length for a 4 step puzzle is 8 characters). Each intermediate string should match the final string a little bit better than the previous one (in terms of the number of letters that are in their final correct positions). There is no “correct” algorithm here-it’s up to you to devise one (i.e. your solution does not need to exactly match the example output given here). Unlike previous Programmer Challenges, this one will be judged primarily on effect, not speed. I’m looking for a smooth transition from startString to endString (and if it’s really fast and small then that’s an extra bonus).

So, who can guess what you get if you rearrange the letters in “Ronald Wilson Reagan”?

Here is Tom’s winning solution to the Nov/Dec Challenge:

// UniqueRGBValues.c:
//   A function that returns the number of
//   unique colors found in a 24-bit RGB image.
// Author: Tom Pinkerton

unsigned long
UniqueRGBValues(Ptr baseAddress,
 short numRows, short numCols)
{
 Handle sBuffers = nil;
 long   sUniquePixels = 0;

// Allocate memory for the data
// structures. We will need:
// 256 x 4 bytes for the unique blue value table.
// 256 x 256 x 8 bytes for the Red/Green
//   intersection grid.
// numRows x numCols x 4 bytes for the
//   master blue list.
 sBuffers = NewHandle((((long)numRows *
  (long)numCols) * 4L) + 525312);
 if (sBuffers != nil) {
 
 // Setup pointers to the data structures.
 long*  sBluListPtr =
  (long*)((char*)*sBuffers + 0);
 long*  sRGTablePtr =
  (long*)((char*)*sBuffers + 1024);
 long*  sRGLinksPtr =
  (long*)((char*)*sBuffers + 525312);
 long*  sRGBase = nil;
 
// Initialize the Red/Green intersection
// grid and the master Blue list with 
// -1's.
 {
 register long*  sInitPtr;
 register long i;
 
// A -1 in this table means that the blue
// value for a particular Red/Green
// combination is not yet found.
 sInitPtr = sBluListPtr;
 i = 64;
 while (i--) {
 sInitPtr[3] =
 sInitPtr[2] =
 sInitPtr[1] =
 sInitPtr[0] = -1;
 sInitPtr += 4;
 }
 
// Only the blue list link need be
// initialized (first of two longs) for
// each element. A -1 means that a unique
// Red/Green pair represented by this
// intersection has not yet been found.
 sInitPtr = sRGTablePtr;
 i = 4096;
 while (i--) {
 sInitPtr[30] =
 sInitPtr[28] =
 sInitPtr[26] =
 sInitPtr[24] =
 sInitPtr[22] =
 sInitPtr[20] =
 sInitPtr[18] =
 sInitPtr[16] =
 sInitPtr[14] =
 sInitPtr[12] =
 sInitPtr[10] =
 sInitPtr[ 8] =
 sInitPtr[ 6] =
 sInitPtr[ 4] =
 sInitPtr[ 2] =
 sInitPtr[ 0] = -1;
 sInitPtr += 32;
 }
 }
 
// Scan the image to create a linked list of blue values at 
// each unique Red/Green intersection. Each element in the
// Red/Green intersection grid consists of the first link 
// of that intersection's blue list (initially -1) and a 
// link to the next Red/Green intersection which contains 
// a blue list. Whereas the Red/Green link is a pointer 
// to the next Red/Green intersection, a blue list link 
// holds an array index in its low order 3 bytes and an 
// actual blue value in its high order byte. The blue link
// index refers to an element in the master blue list. 
// Each master blue list element then points to the next 
// blue value link within a specific blue list or terminates 
// the list with a -1 value.
 {
 register unsigned char*
 sPixelsPtr = (unsigned char*)baseAddress;
 register long* sRGPtr;
 register long*  sLinkPtr = sRGLinksPtr;
 register long sLinkIndex = 0;
 register long sNumPixels = 
 (long)numRows * (long)numCols;
 
// For each pixel in the image, do the following.
 while (sNumPixels--) {
 
// Concatenate the red and green values to create an offset 
// used to point at the unique Red/Green element in the
// Red/Green intersection grid.
 sRGPtr = sRGTablePtr +
  ((((long)sPixelsPtr[1] << 8) |
  (long)sPixelsPtr[2]) << 1);
 
// If this is the first pixel with this particular Red/Green 
// combination, then add the Red/Green intersection to the
// Red/Green linked list.
 if (sRGPtr[0] == -1) {
 sRGPtr[1] = (long)sRGBase;
 sRGBase = sRGPtr;
 }
 
// Create a new blue link with the pixel's blue value and 
// add it to Red/Green intersection's blue list.
 *sLinkPtr = sRGPtr[0];
 sRGPtr[0] = sLinkIndex | ((long)sPixelsPtr[3] << 24);
 
// Increment stuff for the next go 'round.
 ++sLinkPtr;
 ++sLinkIndex;
 sPixelsPtr += 4;
 }
 }
 
// For each list of blue values at a unique Red/Green 
// intersection,  determine the number of unique blue
// values in that list. This calculates the number of unique 
// colors that have the same Red and Green values.
// Accumulating the number of unique colors at every 
// Red/Green intersection gives us the total 
// number of unique colors.
 {
 register long*  sRGPtr = sRGBase;
 register long*  sBlueBase = nil;
 register long*  sBluePtr;
 register long   sLinkIndex;
 
// For each Red/Green intersection found above, do the 
// following.
 while (sRGPtr != nil) {
 
// Walk the list of blue values for this Red/Green pair. 
// For each one, do the following.
 sLinkIndex = sRGPtr[0];
 while (sLinkIndex != -1) {
 
// Create a pointer to the unique blue value element.
 sBluePtr = sBluListPtr +
 ((unsigned long)sLinkIndex >> 24);
 
// A -1 here means that the unique R/G and B color has not 
// yet been counted.  Therefore, mark the fact that it has
// been counted by adding the element to a linked list 
// and incrementing the unique color count. The blue value 
// linked list is used later to quickly reset itself.
 if (*sBluePtr == -1) {
 *sBluePtr = (long)sBlueBase;
 sBlueBase = sBluePtr;
 ++sUniquePixels;
 }
 
// Get the next blue list link in the blue list.
 sLinkIndex = sRGLinksPtr[sLinkIndex & 0x00FFFFFF];
 }
 
// Reset the blue count list by walking its links and 
// replacing them again with -1's.
 sBluePtr = sBlueBase;
 while (sBluePtr != nil) {
 sBlueBase = (long*)*sBluePtr;
 *sBluePtr = -1;
 sBluePtr = sBlueBase;
 }
 sBlueBase = nil;
 
// Get next Red/Green intersection.
 sRGPtr = (long*)sRGPtr[1];
 }
 }
 
 DisposHandle(sBuffers);
 }
 return(sUniquePixels);
}

The Rules

Here’s how it works: Each month there will be a different programming challenge presented here. First, you must write some code that solves the challenge. Second, you must optimize your code (a lot). Then, submit your solution to MacTech Magazine (formerly MacTutor). A winner will be chosen based on code correctness, speed, size and elegance (in that order of importance) as well as the postmark of the answer. In the event of multiple equally desirable solutions, one winner will be chosen at random (with honorable mention, but no prize, given to the runners up). The prize for the best solution each month is $50 and a limited edition “The Winner! MacTech Magazine Programming Challenge” T-shirt (not to be found in stores).

In order to make fair comparisons between solutions, all solutions must be in ANSI compatible C. All entries will be tested with the FPU and 68020 flags turned off in THINK C. When timing routines, the latest version of THINK C will be used (with ANSI Settings plus “Honor ‘register’ first” and “Use Global Optimizer” turned on) so beware if you optimize for a different C compiler.

The solution and winners for this month’s Programmers’ Challenge will be published in the issue two months later. All submissions must be received by the 10th day of the month printed on the front of this issue.

All solutions should be marked “Attn: Programmers’ Challenge Solution” and sent to Xplain Corporation (the publishers of MacTech Magazine) via “snail mail” or preferably, e-mail - AppleLink: MT.PROGCHAL, Internet: progchallenge@xplain.com, and CompuServe: 71552,174. If you send via snail mail, please include a disk with the solution and all related files (including contact information). See page 2 for information on “How to Contact Xplain Corporation.”

MacTech Magazine reserves the right to publish any solution entered in the Programming Challenge of the Month and all entries are the property of MacTech Magazine upon submission. The submission falls under all the same conventions of an article submission.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
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
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel 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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.