Heres how it works: Each month we present a different programming challenge here. First, you write some code that solves the challenge. Second, optimize your code (a lot). Then, submit your solution to MacTech Magazine. We choose a winner 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, well choose one winner at random (with honorable mention, but no prize, given to the runners up). The prize for each months best solution is $50 and a limited-edition The Winner! MacTech Magazine Programming Challenge T-shirt (not available in stores).

To help us make fair comparisons, all solutions must be in ANSI compatible C (e.g. dont use Thinks Object extensions). Use only pure C code. We disqualify any entries with any assembly in them (except for challenges specifically stated to be in assembly). You may call any routine in the Macintosh toolbox (e.g., it doesnt matter if you use NewPtr instead of malloc). We test entries with the FPU and 68020 flags turned off in THINK C. We time routines with the latest THINK C (with ANSI Settings, Honor register first, and Use Global Optimizer turned on), so beware if you optimize for a different C compiler. Limit your code to 60 characters wide. This helps with e-mail gateways and page layout.

We publish the solution and winners for this months Programmers Challenge two months later. All submissions must be received by the 10th day of the month printed on the front of this issue.

MacTech Magazine reserves the right to publish any solution entered in the Programming Challenge of the Month. Authors grant MacTech Magazine the non-exclusive right to publish entries without limitation upon submission of each entry. Authors retain copyrights for the code.

Huffman Decoding

Being able to decode a compressed bit stream quickly is important in many applications. This month youll get a chance to decode one of the most commonly used compression formats around. Huffman codes are variable length bit strings that represent some other bit string. Im not going to explain the algorithm here (see any decent book on algorithms for that) but I will explain the format of the symbol table youll be given and show you how to decode using it (which is all you need to know to do this Challenge).

The symbol table you are passed consists of an array of elements that look like this:

where sym is the compressed bit pattern, symLength is the number of bits in sym (from 1 to 16, starting from the least significant bit of sym) and value is the uncompressed output value (16 bits). The symbol table will be sorted smallest to largest first by length and then, within each length, by sym. For example, if you had a table with two SymElems like this:

and then you were given this compressed bit stream to decode 1100111001001, then the output would be 0xAAAA 0xBBBB 0xAAAA 0xBBBB 0xBBBB because the first two 1 bits are the 2-bit symbol 11 (i.e. 3), and the next 3 bits are the 3-bit symbol 001, and so on.

You will have a chance to create a lookup table in an un-timed init routine but, the amount of memory you can use is variable, from 8K to 256K. Your init routine cannot allocate more than maxMemoryUsage bytes or it will be disqualified (this includes static and global data):

The return value from this init routine will be passed to the actual decode routine (as the privateHuffDataPtr parameter). The decode routine (which is timed) will be called with different sets of compressed data that use the same symbol table:

You can assume that outputPtr points to a buffer large enough to hold all of the uncompressed data. The return value from HuffmanDecode is the actual number of bytes that were stored in that buffer. The input bits are pointed to by bitsPtr and there are numBits of them. The first bit to decode is the most significant bit of the byte pointed to by bitsPtr. TheSymTable and numSyms are the same parameters that were passed to HuffmanDecodeInit.

Two Months Ago Winner

Wow! The competition was really tight for the Erase Scribble Challenge. So tight, in fact, that the 5th place winner was only about 2% slower than the first place winner. But Challenge champion Bob Boonstra (Westford, MA) was able to implement code that was just a tiny bit more efficient than many other highly efficient entries. And, as a bonus, his entry was smaller than all but one of the other entries. Despite his post-publication disqualification from the Factoring Challenge (see below) Bob remains our champion with four 1st place showings (including this one). Congratulations!

Here are the times and code sizes for each entry. 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 time code+data

Bob Boonstra (11) 1363 598

Ernst Munter (3) 1378 1434

John Schlack 1391 1482

Tom Elwertowski (1) 1394 910

Mark Chavira 1395 1538

Jim Sokoloff 1481 1094

Allen Stenger (7) 1911 988

Marcel Rivard 2233 2048

Joshua Glazer 168100 466

At least one contestant pointed out that this Challenge was not entirely realistic because: (1) in a real eraser situation the hit-test routine would return the point that was hit to the caller and, (2) the caller would be removing points from the scribble as segments were erased, thus removing the completely static scribble characteristic of this Challenge. I agree, it would have been more realistic to have a dynamic scribble but I was trying to limit the complexity of the routine (and I was also trying to give clever people a chance to exploit the static nature of the data by using the init routine).

Bobs routine is well commented so I wont discuss it here. He chose an almost identical algorithm to everyone else but he implemented it just a touch better than everyone else.

New Factoring Winner

It seems that Bob Boonstra and I both made mistakes during the Factoring Challenge (June 1994 MacTech): Bob made the mistake of incorrectly handling some input values and I made the mistake of not finding them. Many thanks to Jim Lloyd (Mountain View, CA) for finding this bug and narrowing down the set of inputs that make it happen.

The bug only happens if the number to be factored was created from composite primes where one of them has the high bit set and the other one doesnt. If theyre both set or if theyre both clear then the bug doesnt happen. In case youre using Bobs code, there is a simple fix (thanks, Bob). Change this line:

*prime2Ptr = (x+y)>>1;

to this:

*prime2Ptr = (x>>1) + (y>>1) + 1;

Because of this bug Im going to have to retro-actively disqualify Bobs entry from the Challenge and declare a new winner. However, the new winner is not simply the previous 2nd place winner. The new winner is from a guy whose code was originally sent in a day late (I had to disqualify it) but whose performance is so much better than anyone else who entered (including Bob) that Im going to allow it to win in the interest of having the best possible factoring code published. Its about two orders of magnitude faster than the other entries.

So, our new winner is Nick Burgoyne (Berkeley, CA). It turns out that this Challenge was right up Nicks alley, considering that he has taught factoring math classes in the past. His entry was the only one to use the quadratic sieve algorithm. If youre interested in learning more about this algorithm then Nick recommends a book by David Bressoud, Factorization and Primality Testing, published by Springer-Verlag in 1989. It covers the underlying mathematics and also gives further references to work on the quadratic sieve. It does not assume an advanced background in math. Nick is willing to discuss factoring with anyone who is interested via e-mail. His internet address is: sbrb@cats.ucsc.edu. Congrats, Nick!

Heres Bobs winning solution to the Erase Scribble Challenge, followed by Nicks winning solution to the Factoring Challenge:

scribble.c

/* EraseScribble Copyright (c) 1994 J Robert Boonstra

Problem statement: Determine whether a square eraser of diameter eraserSize centered at the thePoint intersects any of the points in the data structure theScribble. Note that while the problem statement refers to line segments, the definition of a "hit" means that only the endpoints matter.

Solution strategy: The ideal approach would be to create a simple bitMap during Initialization indicating whether an eraser at a given location intersected theScribble. The bitMap would be created by stamping a cursor image at the location of each point in theScribble. However, a bitMap covering the required maximum bounding box of 1024 x 1024 would require 2^17 bytes, or four times as much storage as the 32K we are allowed to use.

Therefore, this solution has three cases:

1) If the actual bounding box for theScribble passed to the init function fits in the 32K available, we create a bitMap as above and use it directly.

2) Otherwise, we attempt to create a half-scale bitMap, where each bit represents 4 pixels in the image, 2 in .h and 2 in .v. In the PtInScribble function, we ca then quickly determine in most cases when the eraser does not intersect theScribble, and we have to walk the points in theScribble if the bitMap indicates a possible hit.

3) In the event there is not enough storage for a half-scale bitmap, we create a quarter-scale bitmap, where each bit represents 16 pixels in the image, 4 in .h and 4 in .v. Then we proceed as in case 2.

To optimize examination of the points in theScribble when the bitmap is not full scale, we sort the points in the initialization function and store them in the privateScribbleDataPtr. Although this reduces the amount of storage available for the bitmap by ~2K, it improves worst case performance significantly.

Although the init function is not timed for score, we have written it in assembler, in the spirit of the September Challenge.

Software Updates via MacUpdate

SpamSieve 2.9.27 - Robust spam filter fo...

SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering.
SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more

VueScan 9.5.62 - 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

Fantastical 2.3.2 - Create calendar even...

Fantastical 2 is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun:
Open Fantastical with a single click or keystroke
Type in your event... Read more

PCalc 4.4.4 - Full-featured scientific c...

PCalc is a full-featured, scriptable scientific calculator with support for hexadecimal, octal, and binary calculations, as well as an RPN mode, programmable functions, and an extensive set of unit... Read more

Alfred 3.2.1 - Quick launcher for apps a...

Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more

OmniPlan 3.6 - Robust project management...

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

Backblaze 4.2.0.990 - Online backup serv...

Backblaze is an online backup service designed from the ground-up for the Mac. With unlimited storage available for $5 per month, as well as a free 15-day trial, peace of mind is within reach with... Read more

AppDelete 4.3.1 - $7.99

AppDelete is an uninstaller that will remove not only applications but also widgets, preference panes, plugins, and screensavers along with their associated files. Without AppDelete these associated... Read more

Apple GarageBand 10.1.4 - Complete recor...

The new GarageBand is a whole music creation studio right inside your Mac -- complete with keyboard, synths, orchestral and percussion instruments, presets for guitar and voice, an entirely... Read more

Adobe Lightroom 6.8 - Import, develop, a...

Adobe Lightroom is available as part of Adobe Creative Cloud for as little as $9.99/month bundled with Photoshop CC as part of the photography package. Lightroom 6 is also available for purchase as a... Read more

Latest Forum Discussions

Galaxy on Fire 3 - Manticore brings the series back for another round of daring space battles. It's familiar territory for folks who are familiar with the franchise. If you've beaten the game and are looking to broaden your horizons, might we... | Read more »

The best apps for your holiday gift exch...

What's that, you say? You still haven't started your holiday shopping? Don't beat yourself up over it -- a lot of people have been putting it off, too. It's become easier and easier to procrastinate gift shopping thanks to a number of apps that... | Read more »

MyTona, based in the chilly Siberian city of Yakutsk, has brought a little festive fun to its hidden object game Seekers Notes: Hidden Mystery. The Christmas update introduces some new inhabitants to players, and with them a chance to win plenty of... | Read more »

PINE GROVE 1.0
Device: iOS Universal
Category: Games
Price: $1.99, Version: 1.0 (iTunes)
Description:
A pine grove where there are no footsteps of people due to continuous missing cases. The case is still unsolved and nothing has... | Read more »

Niantic teases new Pokémon announcement...

After rumors started swirling yesterday, it turns out there is an official Pokémon GO update on its way. We’ll find out what’s in store for us and our growing Pokémon collections tomorrow during the Starbucks event, but Niantic will be revealing... | Read more »

3 reasons why Nicki Minaj: The Empire is...

Nicki Minaj is as business-savvy as she is musically talented and she’s proved that by launching her own game. Designed by Glu, purveyors of other fine celebrity games like cult favorite Kim Kardashian: Hollywood, Nicki Minaj: The Empire launched... | Read more »

Clash of Clans is getting its own animat...

Riding on its unending wave of fame and success, Clash of Clans is getting an animated web series based on its Clash-A-Rama animated shorts.As opposed to the current shorts' 60 second run time, the new and improved Clash-A-Rama will be comprised of... | Read more »

Leaks hint at Pokémon GO and Starbucks C...

Leaked images from a hub for Starbucks employees suggests that a big Pokémon GO event with the coffee giant could begin this very week. The images appeared on Reddit and hint at some exciting new things to come for Niantic's smash hit game.
| Read more »

DietSensor, Inc., a developer of smart food and nutrition applications designed to fight diabetes and obesity and help improve overall fitness, has announced the launch of its DietSensor app for... Read more

Best Buy has dropped their price on the 64GB Apple TV to $159.99 including free shipping. That’s $40 off MSRP.
32GB Apple TVs are on sale right now for $98 on Sams Club’s online store. That’s $51 off... Read more

12-inch Retina MacBooks, Apple refurbished, n...

Apple has restocked a full line of Certified Refurbished 2016 12″ Retina MacBooks, now available for $200-$260 off MSRP. Refurbished 2015 models are available starting at $929. Apple will include a... Read more

Apple has Certified Refurbished 13″ MacBook Airs available starting at $849. An Apple one-year warranty is included with each MacBook, and shipping is free:
- 13″ 1.6GHz/8GB/128GB MacBook Air: $849 $... Read more

Apple refurbished iMacs available for up to $...

Apple has Certified Refurbished 2015 21″ & 27″ iMacs available for up to $350 off MSRP. Apple’s one-year warranty is standard, and shipping is free. The following models are available:
- 21″ 3.... Read more

Apple’s Education discount saves up to $300 o...

Purchase a new Mac or iPad using Apple’s Education Store and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free:
-... Read more

MacTech is a registered trademark of Xplain Corporation. Xplain, "The journal of Apple technology", Apple Expo, Explain It, MacDev, MacDev-1, THINK Reference, NetProfessional, Apple Expo, MacTech Central, MacTech Domains, MacNews, MacForge, and the MacTutorMan are trademarks or service marks of Xplain Corporation. Sprocket is a registered trademark of eSprocket Corporation. Other trademarks and copyrights appearing in this printing or software remain the property of their respective holders. Not responsible for typographical errors.

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.