TweetFollow Us on Twitter

Oct 93 Challenge
Volume Number:9
Issue Number:10
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.


This month we have a straightforward computation challenge: Write a fast ASCII85 encoder. What’s that, you ask? It’s a method of encoding binary data as ASCII characters so that it can be put into things that understand ASCII but not binary data (e-mail messages, for example). It’s also one possible format that EPS files are stored in. If you want your application to be EPS-friendly then you’ll need this routine (as well as the corresponding decoder, which is not part of this challenge).

Here’s how it works: Every 4 bytes of binary data input results in 5 bytes of ASCII character output in the range ! through u. A newline character (0x0D) is inserted in the ASCII output at least once every 80 characters to limit the length of lines. When you have encoded all the binary data, you write out ~> as an end-of-data marker.

More precisely, each set of binary input bytes (b1, b2, b3, b4) produces a set of encoded ASCII characters (c1, c2, c3, c4, c5) such that:

(b1 * 2563) + (b2 * 2562) + (b3 * 256) + b4 =
(c1 * 854) + (c2 * 853) + (c3 * 852) + (c4 * 85) + c5

So, the 4 bytes of binary data are a base-256 number that are converted into 5 bytes of a base-85 number. The 5 digits of this number (c1..c5) are then converted to ASCII by adding 33, the ASCII code of !. ASCII characters in the range of ! to u are used, where ! represents the value 0 and u represents the value 84. There is one special case where if all 5 digits are zero they are encoded as a single character z instead of !!!!!.

If the size of the input binary data is not a multiple of 4 then the final set of output bytes are created by taking the n input bytes (1, 2 or 3) and padding with 4-n zero bytes and then converting the result to ASCII85 normally but without applying the special z case. Then, write out n+1 bytes of the resulting ASCII85 data, followed immediately by the ~> marker. This allows an ASCII85 decoder to know the actual number and values of all real input bytes.

The prototype of the function you write is:

void ASCII85Encode(inputPtr, 
 numInputBytes, outputPtr, 
char    *inputPtr;
unsigned long    numInputBytes;
char    *outputPtr;
unsigned long    *numOutputBytesPtr;

The inputPtr and numInputBytes describe the binary data input (numInputBytes will average about 64K). You fill the buffer pointed to by outputPtr with the ASCII85 data you create. The buffer is allocated for you and is big enough to handle the worst case output, given numInputBytes. You set *numOutputBytesPtr equal to the total number of bytes you put in the buffer (including the 2 for the end-of-data marker).


Perhaps I should re-emphasize that correctness is the first criteria for a winning solution. I had to disqualify 6 out of the 17 entries I received for the Replace All challenge because they lacked correctness. Be sure to test your entries with a range of inputs, please, if you’re serious about wanting to win.

Of the 11 who survived my test suite (which was not really that severe) there were four that were very close in speed. The one who came out a little faster than the others most of the time was from Tom Elwertowski (Cambridge, MA) who makes the observation that if the replacement length is not greater than the source length then you can replace strings as you find them; otherwise you have to find all the matches in a first pass and then do a second pass to make the actual replacements (back to front). Bill Karsh (location unknown) deserves mention for coming in fastest almost as often as Tom when the replacement string was equal to or shorter than the source string. However, for some cases where the replacement string was longer than the source string his code was near the bottom of the pack (the times given below are average times for all test cases).

A couple of people were quick to realize that the ROM’s Munger trap could be used to solve this puzzle. However as the table below shows, it’s possible to do much better, in terms of speed, if you don’t use Munger (‘*’ = an entry that used Munger for at least part of the solution; ‘**’ = an entry that was all Munger). Using Munger does make for small code though.

Here are the average times and sizes (numbers in parens after a person’s name indicate how many times that person has finished in the top 5 places of all previous programmer challenges, not including this one):

Name bytes avg ticks

Tom Elwertowski 864 54

Jeff Mallett (2) 770 60

Gerry Davis (1) 1042 64

Bill Karsh 1320 69

Stepan Riha (3) 1132 92

Jan Bruyndonckx 826 101

David Rand * 880 140

Bob Boonstra (2) 528 188

Dave Darrah ** 90 301

John Baxter ** 122 313

Eric Josserand 572 343

There are really 3 cases you need to think about to write a fast ReplaceAll: (1) replacement string and source string are the same length, (2) replacement string is shorter than the source string and (3) replacement string is longer than the source string. The first is the fastest; you just overwrite the source string with the replacement string in place and you don’t need to move any other bytes. The second case is almost as fast; you overwrite the source string with a shorter replacement string and then degap the Handle by the difference in lengths (of course, you cumulatively degap as you find/replace, and not completely degap after each individual replace). The third case is the slowest because it requires two passes to do it efficiently: during the first pass you find all occurrences of the source string and mark them (or keep an array of their positions), then you grow the Handle by the difference in lengths between the replacement string and the source string times the number of occurrences of the source string you found; then you start at the back of the Handle moving bytes and making replacements as you go. This guarantees a minimum of Handle resizing and gapping.

In addition, if you are motivated, you could add the special case code that Bill Karsh did that checks for replacement and source strings of length exactly equal to 1 and have a tiny little loop that screams for that case (which will catch those reviewers who time the real-world, every-day case of changing a page of “a”s into a page of “b”s to make their word processing speed comparison charts). And you could add a table driven search algorithm like Stepan Riha (Austin, TX) did that minimizes search time in cases where partial matches are common.

Or you could forget all that and listen to John Baxter (location unknown) who says “There is, IMHO, too much optimization and too little problem solving going on in the world (but I do enjoy the challenge feature and your optimization series). Clearly SOME optimization has its place, but the last time I routinely cared about squeezing the last possible cycle OR storage location out of code was about 1959.” Well, John, I can see your point but as a user who does ReplaceAlls on 200 page documents fairly often I can assure you that optimizing that operation is time well spent.

Here’s Tom’s winning solution:

/* Tom Elwertowski
 * ReplaceAll( sourceHndl, replaceHndl, targetHndl )
 * Replace all occurrances of sourceHndl in targetHndl with
 * replaceHndl. If replace length is not greater than source
 * length, replacement can be done as search proceeds.
 * Otherwise, all occurrances must be found first in order
 * to determine how much target will grow. A recursive
 * solution is used in the latter case; matches are found
 * on the way in and replacement occurs on the way out.
 * Depending upon run length, substrings are moved either
 * by a byte copy loop or by the BlockMove routine. A word
 * move loop was considered and rejected. Best performance
 * was achieved for these string sizes: byte loop: <9,
 * word loop: 9-200 and BlockMove: >200. A word loop must
 * check for and deal with word nonaligmnent however which
 * resulted in more than a few lines of code and an inline
 * solution appeared excessively cumbersome. When all three
 * approaches were put in a subroutine, the additional
 * overhead swamped the gain in most cases. The compromise
 * was to use inline code with a byte loop for substrings
 * up to 21 characters and a BlockMove otherwise.

#define kBlockMoveMin 22

typedef struct replaceParamBlock {
 Handle sourceHndl;
 long sourceSize;
 char *sourceStart;
 char *sourceEnd;
 Handle replaceHndl;
 long replaceSize;
 char *replaceStart;
 char *replaceEnd;
 Handle targetHndl;
 long targetSize;
 char *targetStart;
 char *targetEnd;
 long deltaSize;
} replaceParamBlock, *replaceParamBlockPtr;

long replaceOne( char *target, long depth, long deltaOffset,
 replaceParamBlockPtr replacePBPtr);

long ReplaceAll( Handle sourceHndl, Handle replaceHndl,
 Handle targetHndl )
 replaceParamBlock replacePB;
 char *target, *targetMatch, *targetOld, *targetNew,
 *source, *replace;
 long numReplace, deltaOffset, size;

 replacePB.sourceHndl = sourceHndl;
 replacePB.sourceSize = GetHandleSize( sourceHndl);
 replacePB.sourceStart = *sourceHndl;
 replacePB.sourceEnd =
 replacePB.sourceStart + replacePB.sourceSize;
 replacePB.replaceHndl = replaceHndl;
 replacePB.replaceSize = GetHandleSize( replaceHndl);
 replacePB.replaceStart = *replaceHndl;
 replacePB.replaceEnd =
 replacePB.replaceStart + replacePB.replaceSize;
 replacePB.targetHndl = targetHndl;
 replacePB.targetSize = GetHandleSize( targetHndl);
 replacePB.targetStart = *targetHndl;
 replacePB.targetEnd = 
 replacePB.targetStart + replacePB.targetSize;
 replacePB.deltaSize =
 replacePB.replaceSize - replacePB.sourceSize;

 numReplace = 0;
 deltaOffset = 0;
 if ( replacePB.deltaSize <= 0 ) {

 /* Iterative solution when 
  * replacement not longer then source */
 target = replacePB.targetStart;
 while ( target < replacePB.targetEnd) {
 if ( *target++ == *replacePB.sourceStart ) {

 /* Beginning of potential match */
 targetMatch = target - 1;
 source = replacePB.sourceStart + 1;
 while ( source < replacePB.sourceEnd )
 if ( *target++ != *source++ )
 goto noMatch;

 /* Match encountered */

 /* Shift unchanged segment of  target */
 if (numReplace > 0 &&
 replacePB.deltaSize < 0 ) {
 targetOld = replacePB.targetStart;
 targetNew = replacePB.targetStart +
 size = targetMatch -
 if ( size < kBlockMoveMin )
 while ( targetOld < targetMatch )
 *targetNew++ = *targetOld++;
 BlockMove( targetOld, targetNew,
 size );

 /* Do replacement */
 replace = replacePB.replaceStart;
 targetNew = targetMatch + deltaOffset;
 if ( replacePB.replaceSize < kBlockMoveMin )
 while ( replace < replacePB.replaceEnd )
 *targetNew++ = *replace++;
 BlockMove( replace, targetNew,
 replacePB.replaceSize );

 deltaOffset += replacePB.deltaSize;
 replacePB.targetStart = target;


 /* End of target encountered */

 /* If replacements have occurred and
  * replacement is shorter */
 if ( numReplace > 0 && replacePB.deltaSize < 0 ) {

 /* Compress target from last match to end */
 targetNew = replacePB.targetStart + deltaOffset;
 targetOld = replacePB.targetStart;
 size = replacePB.targetEnd -
 if ( size < kBlockMoveMin )
 while ( targetOld < replacePB.targetEnd )
 *targetNew++ = *targetOld++;
 BlockMove( targetOld, targetNew, size );

 /* Resize target*/
 SetHandleSize ( targetHndl,
 replacePB.targetSize += deltaOffset );
 if ( MemError() != noErr)
 numReplace = -1;
 /* Recursive solution when
  * replacement is longer than source */
 numReplace = replaceOne( replacePB.targetStart,
 0, 0, &replacePB );
 return ( numReplace );

long replaceOne( char *targetEntry, long depth,
 long deltaOffset, replaceParamBlockPtr replacePBPtr )
 char *source, *replace, *target;
 char *targetOld, *targetNew, *targetMatch;
 long targetEntryOffset, targetMatchOffset, size;
 long numReplace;
 target = targetEntry;
 targetEntryOffset = targetEntry -
 while ( target < replacePBPtr->targetEnd ) {
 if ( *target++ == *replacePBPtr->sourceStart ) {

 /* Beginning of potential match */
 targetMatch = target - 1;
 targetMatchOffset = targetMatch -
 source = replacePBPtr->sourceStart + 1;
 while ( source < replacePBPtr->sourceEnd )
 if ( *target++ != *source++ )
 goto noMatch;

 /* Match encountered. Look for next match */
 numReplace = replaceOne( target, depth + 1,
 deltaOffset + replacePBPtr->deltaSize,
 replacePBPtr );

 /* Expand target after all matches found */
 if ( numReplace > 0 ) {

 /* Do replacement */
 targetMatch = replacePBPtr->targetStart +
 targetNew = targetMatch + deltaOffset;
 if ( replacePBPtr->replaceSize <
 kBlockMoveMin ) {
 targetNew += replacePBPtr->replaceSize;
 replace = replacePBPtr->replaceEnd;
 while ( replace >
 replacePBPtr->replaceStart )
 *--targetNew = *--replace;
 BlockMove( replacePBPtr->replaceStart,
 replacePBPtr->replaceSize );

 /* Shift unchanged segment of target */
 if ( depth > 0 ) {
 targetOld = targetMatch;
 targetEntry =
 replacePBPtr->targetStart +
 size = targetMatch - targetEntry;
 if ( size < kBlockMoveMin )
 while ( targetOld > targetEntry )
 *--targetNew = *--targetOld;
 else {
 targetNew -= size;
 BlockMove( targetEntry, targetNew,
 size );
 return ( numReplace );

 /* End of target encountered */
 if ( depth > 0 ) {

 /* Resize target */
 SetHandleSize ( replacePBPtr->targetHndl,
 replacePBPtr->targetSize += deltaOffset );
 if ( MemError() == noErr) {
 /* Update pointers after possible relocation */
 replacePBPtr->targetStart =
 replacePBPtr->targetEnd =
 replacePBPtr->targetStart +
 replacePBPtr->replaceStart =
 replacePBPtr->replaceEnd =
 replacePBPtr->replaceStart +

 /* Expand target from last match to end */
 targetOld = replacePBPtr->targetEnd -
 targetEntry = replacePBPtr->targetStart +
 size = targetOld - targetEntry;
 if ( size < kBlockMoveMin ) {
 targetNew = replacePBPtr->targetEnd;
 while ( targetOld > targetEntry )
 *--targetNew = *--targetOld;
 else {
 targetNew = targetEntry + deltaOffset;
 BlockMove( targetEntry, targetNew, size );
 depth = -1;

 return ( depth );

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 (i.e., don’t use Think’s Object extensions). Only pure C code can be used. Any entries with any assembly in them will be disqualified (except for those challenges specifically stated to be in assembly). However, you may call any routine in the Macintosh toolbox you want (i.e., it doesn’t matter if you use NewPtr instead of malloc). 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. All code should be limited to 60 characters wide. This will aid us in dealing with e-mail gateways and page layout.

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:, CompuServe: 71552,174 and America Online: MT PRGCHAL. 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

Vivaldi 1.9.818.44 - An advanced browser...
Vivaldi is a browser for our friends. In 1994, two programmers started working on a web browser. Our idea was to make a really fast browser, capable of running on limited hardware, keeping in mind... Read more
Skim 1.4.29 - PDF reader and note-taker...
Skim is a PDF reader and note-taker for OS X. It is designed to help you read and annotate scientific papers in PDF, but is also great for viewing any PDF file. Skim includes many features and has a... Read more
1Password 6.7.1 - Powerful password mana...
1Password is a password manager that uniquely brings you both security and convenience. It is the only program that provides anti-phishing protection and goes beyond password management by adding Web... Read more
FontExplorer X Pro 6.0.2 - Font manageme...
FontExplorer X Pro is optimized for professional use; it's the solution that gives you the power you need to manage all your fonts. Now you can more easily manage, activate and organize your... Read more
VOX 2.8.24 - Music player that supports...
VOX just sounds better! The beauty is in its simplicity, yet behind the minimal exterior lies a powerful music player with a ton of features and support for all audio formats you should ever need.... Read more
OmniPlan 3.7.1 - Robust project manageme...
With OmniPlan, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success,... Read more
Dropbox 24.4.17 - Cloud backup and synch...
Dropbox is an application that creates a special Finder folder that automatically syncs online and between your computers. It allows you to both backup files and keep them up-to-date between systems... Read more
WhatsApp 0.2.4238 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
SteerMouse 5.1 - Powerful third-party mo...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
OmniPlan Pro 3.7.1 - Professional-grade...
With OmniPlan Pro, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success... Read more

Latest Forum Discussions

See All

Fire Emblem Heroes event announces new m...
As reported yesterday, Nintendo was gearing up a live press event for their popular mobile game,Fire Emblem Heroes. While the stream revealed a lot of new things, the event was entirely in Japanese. Luckily we have a rundown of what was announced... | Read more »
Best games we played this week
Another week, another slate of new mobile games. Although there weren't as many big name releases as last week, there were plenty of unique video game titles that came out that's sure to keep you interested over the weekend. Everything from classic... | Read more »
Olli by Tinrocket (Photography)
Olli by Tinrocket 1.0 Device: iOS iPhone Category: Photography Price: $2.99, Version: 1.0 (iTunes) Description: Get drawn in with Olli by TinrocketOlli instantly turns your everyday moments into hand-drawn art and animations. • Watch... | Read more »
Penarium (Games)
Penarium 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: | Read more »
Fire Emblem Heroes is way more profitabl...
Profits for Nintendo's mobile game Fire Emblem Heroes are apparently impressive enough to beat out other Nintendo titles likeSuper Mario Run, despite having 10 times fewer downloads. [Read more] | Read more »
Classic series Robot Unicorn Attack 3 no...
The classic Adult Swim browser game, Robot Unicorn Attack, branched off into a series of popular mobile games. Now, the latest entry into the series, Robot Unicorn Attack 3, is available for iOS and Android mobile devices. [Read more] | Read more »
Sudoku Sweeper (Games)
Sudoku Sweeper 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: A minimalist mashup of Minesweeper and Sudoku. Logic puzzle perfection. Every row, column and zone contains a bomb and one of... | Read more »
Under Leaves (Games)
Under Leaves 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Journey into the forest, the jungle or the depths of the deep blue sea. Find chestnuts for the pigs, a caterpillar for the... | Read more »
Ninja Pizza Girl (Games)
Ninja Pizza Girl 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: In the not-so-distant future, rampart traffic congestion has resulted in only one way to deliver pizzas across town in thirty... | Read more »
SCRAP (Games)
SCRAP 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: That day, for no apparent reason, SCRAP decided to wake up and run. He had to, because his activation was a mistake the "Factory" could... | Read more »

Price Scanner via

13-inch 2.9GHz/256GB Space Gray Touch Bar Mac...
B&H Photo has the 13″ 2.9GHz/256GB Space Gray Touch Bar MacBook Pro in stock today and on sale for $150 off MSRP including free shipping plus NY & NJ sales tax only: - 13″ 2.9GHz/256GB Touch... Read more
21-inch iMacs on sale for up to $151 off MSRP
B&H Photo has 21″ iMacs on sale for up to $151 off MSRP, each including free shipping plus NY sales tax only: - 21″ 3.1GHz iMac 4K: $1348 $151 off MSRP - 21″ 2.8GHz iMac: $1199.99 $100 off MSRP... Read more
Weekend deal: Up to $420 off new MacBook Pros...
Apple has Certified Refurbished 2016 15″ and 13″ MacBook Pros available for $230 to $420 off original MSRP. An Apple one-year warranty is included with each model, and shipping is free: - 15″ 2.6GHz... Read more
Price drop: 15-inch 2.2GHz Retina MacBook Pro...
Amazon has dropped their price on 15″ 2.2GHz Retina MacBook Pros (MJLQ2LL/A) to $1709.99 including free shipping. Their price is $290 off MSRP for this model. Note that stock may sell out quickly at... Read more
2.8GHz Mac mini on sale for $899, save $100
B&H Photo has the 2.8GHz Mac mini (model number MGEQ2LL/A) on sale for $899 including free shipping plus NY & NJ sales tax only. Their price is $100 off MSRP. Read more
Check Apple prices on any device with the iTr...
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
New System Clock for macOS by B-Eng Now Avail...
Fehraltorf, Switzerland based B-Eng has announced the release and immediate availability of System Clock, the company’s new system monitor and information app developed exclusively for macOS. System... Read more
DEVONtechnologies Celebrates 15th Anniversary...
DEVONtechnologies celebrates its 15th company anniversary with a 30% discount on all its software products from May 1st through 5th, 2017. In spring 2002, DEVONtechnologies opened its website and... Read more
WaterField Designs Invites Customers to Help...
San Francisco based WaterField Designs invites customers and air travelers to participate in developing the next generation in-flight travel case, the Air Porter. Frustrated with limited legroom,... Read more
Save up to $260 with Apple refurbished 12-inc...
Apple has Certified Refurbished 2016 12″ Retina MacBooks available for $200-$260 off MSRP. Apple will include a standard one-year warranty with each MacBook, and shipping is free. The following... Read more

Jobs Board

*Apple* Mobile Master - Best Buy (United Sta...
**501505BR** **Job Title:** Apple Mobile Master **Location Number:** 000849-Gurnee-Store **Job Description:** **What does a Best Buy Apple Mobile Master do?** At Read more
Best Buy *Apple* Computing Master - Best Bu...
**498428BR** **Job Title:** Best Buy Apple Computing Master **Location Number:** 000293-Rockville-Store **Job Description:** **What does a Best Buy Apple Read more
*Apple* Mac Computer Technician - GeekHampto...
…complex computer issues over the phone and in person? GeekHampton, Long Island's Apple Premium Service Provider, is looking for you! Come work with our crew Read more
*Apple* Retail - Multiple Positions- Chicago...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Systems Engineer - California Polyte...
Cal Poly, San Luis Obispo Apple Systems Engineer Department: ITS - Customer & Tech Support (134900) College/Division: Academic Affairs Salary Range: Position Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.