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.

## ASCII85 ENCODING

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,
numOutputBytesPtr)
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).

## TWO MONTHS AGO WINNER

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 +
deltaOffset;
size = targetMatch -
replacePB.targetStart;
if ( size < kBlockMoveMin )
while ( targetOld < targetMatch )
*targetNew++ = *targetOld++;
else
BlockMove( targetOld, targetNew,
size );
}

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

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

noMatch:;
}

/* 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 -
replacePB.targetStart;
if ( size < kBlockMoveMin )
while ( targetOld < replacePB.targetEnd )
*targetNew++ = *targetOld++;
else
BlockMove( targetOld, targetNew, size );

/* Resize target*/
SetHandleSize ( targetHndl,
replacePB.targetSize += deltaOffset );
if ( MemError() != noErr)
numReplace = -1;
}
}
else
/* 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 -
replacePBPtr->targetStart;
while ( target < replacePBPtr->targetEnd ) {
if ( *target++ == *replacePBPtr->sourceStart ) {

/* Beginning of potential match */
targetMatch = target - 1;
targetMatchOffset = targetMatch -
replacePBPtr->targetStart;
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 +
targetMatchOffset;
targetNew = targetMatch + deltaOffset;
if ( replacePBPtr->replaceSize <
kBlockMoveMin ) {
targetNew += replacePBPtr->replaceSize;
replace = replacePBPtr->replaceEnd;
while ( replace >
replacePBPtr->replaceStart )
*--targetNew = *--replace;
}
else
BlockMove( replacePBPtr->replaceStart,
targetNew,
replacePBPtr->replaceSize );

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

/* 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->targetHndl;
replacePBPtr->targetEnd =
replacePBPtr->targetStart +
replacePBPtr->targetSize;
replacePBPtr->replaceStart =
*replacePBPtr->replaceHndl;

replacePBPtr->replaceEnd =
replacePBPtr->replaceStart +
replacePBPtr->replaceSize;

/* Expand target from last match to end */
targetOld = replacePBPtr->targetEnd -
deltaOffset;
targetEntry = replacePBPtr->targetStart +
targetEntryOffset;
size = targetOld - targetEntry;
if ( size < kBlockMoveMin ) {
targetNew = replacePBPtr->targetEnd;
while ( targetOld > targetEntry )
*--targetNew = *--targetOld;
}
else {
targetNew = targetEntry + deltaOffset;
BlockMove( targetEntry, targetNew, size );
}
}
else
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: progchallenge@xplain.com, 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:

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