TweetFollow Us on Twitter

Jan 97 Challenge

Volume Number: 13 (1997)
Issue Number: 1
Column Tag: Programmer's Challenge

Programmer's Challenge

By Bob Boonstra, Westford, MA


The theme of this issue of the magazine is the Be Operating System, so it seemed appropriate to focus the Challenge on the BeOS, and give you a chance to use the BeOS for Macintosh CD-ROM bundled in this issue. Since the BeOS will be new to most of you, this Challenge will be a simple one. The problem is to write a window class that will display and sort a list of strings by one of three specified methods: a bubble sort, an exchange sort, and an algorithm of your choosing. The prototype for the class you should write is

typedef enum SortType {
 kBubbleSort = 1,
 kExchangeSort = 2,
 kMySort = 3
} SortType;

class SortWindow : public BWindow {

 SortWindow(BRect frame); 
virtual void   DoSort(
 char *thingsToSort[],  /* list of strings to sort, also returns sorted list */
 int numberOfThings, /* number of thingsToSort */
 SortType sortMethod);  /* sort method to use */

My test code will open three instances of your window class and ask each one to sort a copy of the same list of strings: one by the kBubbleSort method, one by kExchangeSort, and one by kMySort. Your SortWindow constructor should create a BListView and attach it to your SortWindow. When the DoSort method is invoked, you should display the thingsToSort and sort them into ascending ASCII order by the sortMethod algorithm. Each time two thingsToSort are exchanged, the BListView display should be updated. When the sort is complete, DoSort should post a B_QUIT_REQUESTED message to the application. The list should be sorted in place and returned in thingsToSort.

This will be a native PowerPC Challenge, using the latest Macintosh CodeWarrior environment, targeted for the BeOS. Solutions must be coded in C++. The code will be tested on my 8500 using the BeOS. (In the event I cannot get the BeOS to run on my Mac, I will run the tests on a 2x133MHz BeBox with one processor disabled.) The winner will be the solution that completes all three sorts correctly in the minimum time.

Three Months Ago Winner

Congratulations to Andy Antoniewicz (Mountain View, CA) for narrowly beating second and third place finishers Greg Cooper and Ludovic Nicolle in the October DNA Match Challenge. Of the fifteen entries I received for this Challenge, ten worked completely correctly, two were partially correct, and the remaining three crashed my machine.

Recall that the DNA Match Challenge was essentially a string matching problem, where the strings were allowed to differ in a specified number of positions (or fewer). The object was to return the number of near matches of a fragment string found in a reference database string.

My intent had been to test the solutions submitted using very long database strings. The run times of the solutions imposed a practical limit of about 2 MB on the size of the database string in an individual test case. The fragments to be matched were all significantly shorter than the database string, as indicated in the problem statement. The tests ranged from requiring very accurate matches, with a small value for the number of differences allowed, to approximate matches that could differ in up to half of the characters in the reference string.

The problem statement allowed for a timed initialization routine that would be executed once prior to testing matches against multiple fragments for a given database string. None of the top-ranked solutions made any significant use of this option, although a number of people used it to initialize small translation tables. Several people commented that it was difficult to find a use for this initialization routine, when the scratch storage provided was smaller than the maximum size database string.

Andy's winning entry parses the fragment string to create, for each character in the DNA "alphabet", a list of offsets where that character is located in the fragment. He then walks the database string and increments a match counter for each possible alignment of the fragment that matches the database at that character position. Andy uses a circular buffer twice the size of the fragment to store the match counts, which allows him to perform bounds checking on that buffer only once per database character, rather than within the innermost character matching loop. I had to read the code several times and run through a few cases manually before the light went on and I understood the algorithm, after which I found it quite clever.

While A.C.C. Murphy's solution did not place in the top five, one of his algorithms used a refinement worthy of note. He kept a running total of the counts of characters in a fragment-sized segment of the database, only checking for a specific match if the frequency counts were close enough to those of the fragment. In test cases where the character frequencies of the fragment were significantly different than much of the database, this technique might have done very well.

The table below summarizes the results for each correct or partially correct entry, including total execution time for all of the test cases and code size. Numbers in parenthesis after a person's name indicate that person's cumulative point total for all previous Challenges, not including this one. An asterisk indicates a result that was partially correct and therefore not eligible to win.

NameLanguageTotal TimeCode Size
Andy Antoniewicz (4)C123823728
Greg Cooper (17)C126233872
Ludovic Nicolle (14)C126646528
Michael Panchenko (6)C148243800
Bjorn Davidsson (4)C149171424
A.C.C. Murphy (10)C1510861800
Ernst Munter (224)C++176521752
Peter Lewis (32)C195312240
Mark DayC197385848
Larry Landry (29)C2671181376
Alan Hart (*)C210701848
Xin Xu (*)C2230151576


Here are the Top 20 Contestants for the Programmer's Challenge. The numbers below include points awarded over the 24 most recent contests, including points earned by this month's entrants.

1.Munter, Ernst193
2.Gregg, Xan114
3.Larsson, Gustav87
4.Lengyel, Eric40
5.[Name deleted]40
6.Lewis, Peter32
7.Boring, Randy27
8.Cooper, Greg27
9.Antoniewicz, Andy24
10.Beith, Gary24
11.Kasparian, Raffi22
12.Cutts, Kevin21
13.Nicolle, Ludovic21
14.Picao, Miguel Cruz21
15.Brown, Jorg20
16.Gundrum, Eric20
17.Karsh, Bill19
18.Stenger, Allen19
19.Mallett, Jeff17
20.Nevard, John17

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 place20 points
2nd place10 points
3rd place7 points
4th place4 points
5th place2 points
finding bug2 points
suggesting Challenge2 points

Here is Andy's winning solution:


© 1996 Andy Antoniewicz

DNA string match with wildcard & constant distance

No setup calculations on the database are performed. It seemed kind of pointless to attempt the equivalent 
of a 50 to 1 loss, less compression of the database ( it was 1000 to 1 for the first problem statement ).

This is a simple and quick single byte per pass index and count type algorithm. It uses three tables: a byte 
to code index table "aTable", a fragment index list array "alphaList",
and a hit count circular array "matchQueue". A precursor list is built and used once to build the alphaList 
array, and I do not clean up after (plenty of allocated storage).
Once built, the aTable contains an index into the alphaList for each given alphabet letter in the fragment. 
The alphaList contains a sequential list of all occurrences of that character in the fragment string.

The algorithm then increments the match count for all possible alignments of the fragment for each database 
character. Since the maximum misalignment is less than the fragment size, only the previous fragmentSize 
database characters need to be considered for matches at any particular time. Hence the circular queue 

The database search execution time is order( pN ) where N = number of database characters
p = average fragment entries per alphabet char 
( for example: A=3,C=3,G=2,T=2 -
> p = 2.5 )
The storage used is almost totally dependent on the fragment size. Storage used in bytes
    = 20     ( storage struct )
    + 256         ( 16bit aTable )
    + 2 * fragment chars( 16bit precursor )
    + 2 * fragment chars( 16bit alphaList )
    + 2 * alphabet chars (  more alphaList )
    + 4 * fragment chars( 2x16bit matchQueue )

 ********* ********* ********* ********* ********* ********/
#define kAlphaTableSize   128
#define kEndOfAlphaList   -1
typedef struct {
 long storageSize; // total storage available
 long usedStorage; // total storage used
 long fragmentSize;// size in chars of fragment
 short  *alphaList;// start of fragment index list
 short  *matchQueue; // start of match count queue
 short  alphaTable[ kAlphaTableSize ];
 short  precursor[]; // start of match count queue
} DNAStore;

/********* ********* ********* ********* ********* ********
 Function Prototypes
 ********* ********* ********* ********* ********* ********/

void InitMatch(
 char *alphabet, // legal characters in database
 char *database, // the reference database
 void *storage,  // pre-allocated storage
 long storageSize// size of storage in bytes

long FindMatch(  // return number of matches
 char *alphabet, // legal characters in database
 char *database, // the reference database
 void *storage,  // pre-allocated storage
 char *fragment, // the fragment to find
 long diffsAllowed,// num of diffs allowed between
    //  a "match" and the database
 long matchPosition[]// match return array

void BuildAlphaList(
 char   *alphabet, // legal characters in database
 char   *fragment, // the fragment to find; 0 term
 DNAStore *storage // my storage area

/********* ********* ********* ********* ********* ********
 * InitMatch
 * This routine does nothing except to store the
 *  size of memory allocated by the calling program.
 * All of the structures used are based on the fragment
 * to be searched for.
 ********* ********* ********* ********* ********* ********/

void InitMatch(
 char *alphabet, // legal characters in database
 char *database, // the reference database
 void *storage,  // pre-allocated storage
 long storageSize// size of storage in bytes
 ((DNAStore*)storage)->storageSize = storageSize;
}// end of InitMatch

/********* ********* ********* ********* ********* ********
 * BuildAlphaList
 * This routine has three parts:
 * Build the AlphaTable
 * The AlphaTable is an index table used to find
 * the start location inside the AlphaList
 * that corresponds to the given alphabet
 * character.
 * Build the AlphaList precursor
 * This is a linked list of the indexes to each
 * character in the fragment. It is used once
 * to build the AlphaList and never re-used.
 * Build the AlphaList
 * This is a sorted list of indexes for each
 * alphabet character. The head of each list is
 * stored in the AlphaTable, and each list is
 * ended by a -1.
 ********* ********* ********* ********* ********* ********/

void BuildAlphaList(
 char   *alphabet, // legal characters in database
 char   *fragment, // the fragment to find; 0 term
 DNAStore *storage // my storage area
 short  *aTable; // ptr in the AlphaTable
 short  *precursor;// the AlphaList precursor
 short  *alphaList;// the AlphaList

 char *aString;  // ptr to a character string
 long aChar;// a character from a string
 long count;
 short  index;

     * Initialize alphabet entries to kEndOfAlphaList
     *     Proper function for characters not in the alphabet
     *     requires that the other entries be preset to zero.
     *     This is automatic if the storage is cleared by
     *     the calling program and if the alphabet does not
     *     change between calls to InitMatch.
 aTable = storage->alphaTable;
 aString = alphabet - 1;
 while( (aChar = (long)(*(++aString)) ) > 0x00 )
 *(aTable+aChar) = kEndOfAlphaList;
     * Build precursor linked index list
     *     This list is only used to produce the 
     *     AlphaList below. The precursor and
     *     the AlphaList are rebuilt for each
     *     new fragment that will be searched for.
 precursor= storage->precursor;
 aString= fragment - 1;
 index  = 0;
 count  = 0;
 while( (aChar = (long)(*(++aString))) > 0x00 )
 index = *(aTable+aChar); // get prev head
 *(aTable+aChar) = count; // put new head
 *(precursor+count) = index;// store prev head
 storage->fragmentSize = count;
     * Build AlphaList
     *     by walking each alphabet character's precursor 
     *     list and writing the index list into the 
     *     AlphaList the algorithm gets a sorted list of
     *     indexes into the fragment for each letter in the
     *     alphabet. The aTable will point to the first entry
     *     in the AlphaList and the last entry of each 
     *     character list is equal to the constant 
     *     kEndOfAlphaList ( = -1 ). Note that AlphaList
     *     location 0 is used to ignore database characters
     *     which are not in the given alphabet (it was free).
 alphaList = precursor + count;
 *(alphaList) = kEndOfAlphaList;
 aString = alphabet - 1;
 count = 1;
 while( (aChar = (long)(*(++aString)) ) > 0x00 )
 index = *(aTable+aChar);
 *(aTable+aChar) = count;
 while( index != kEndOfAlphaList )
 *(alphaList+count) = index;
 index = *(precursor+index);
 *(alphaList+count) = kEndOfAlphaList;
 storage->alphaList= alphaList;
 storage->matchQueue = alphaList + count + 1;
}// end of BuildAlphaList

/********* ********* ********* ********* ********* ********
 * FindMatch
 * For each character in the database increment every
 * match count that has the same character ( a hit ).
 * If after all possible alignments have been tallied,
 * the match count is greater than or equal to the value
 * of the threshold, then a match has been found.
 * Add the matching entry to the return array and continue
 * until all database characters have been tested.
 ********* ********* ********* ********* ********* ********/

long FindMatch(  // return number of matches
 char *alphabet, // legal characters in database
 char *database, // the reference database
 void *storage,  // pre-allocated storage
 char *fragment, // the fragment to find
 long diffsAllowed,// num of diffs allowed between
    //  a "match" and the fragment
 long matchPosition[]// match return array
 DNAStore *theStore; // typed storage
 short  *matchTop; // top of match array
 short  *matchCur; // current match array entry
 short  *aTable; // alpha to aList index table
 short  *aList;  // array of hit offsets
 short  *hitOffset;// current hit offset entry
 char   *dbString; // current database char entry
 long   dbChar;  // current database character
 long   count;   // current database location
 long   numMatch;// number of matches found
 long   fragSize;// fragment size in bytes
 long   loop;    // loop counter
 long   hitPos;  // current hit offset position
 long   threshold; // the threshold for matching
 theStore = (DNAStore*)storage;
 BuildAlphaList( alphabet,fragment,theStore);
 fragSize = theStore->fragmentSize;
 matchTop = theStore->matchQueue;
 matchCur = matchTop + fragSize;
 = (long)(matchCur+fragSize)-(long)theStore;
     * Clear the Match Count Array
     *     clear out the match counts for the entire array
 for( count=0; count<fragSize; count++ )
 *(matchCur+fragSize) = 0;
 *matchCur- = 0;

     * Walk the Database
     *    The match count array is a double size circular
     *    queue of match counts. It is double size so I do
     *    not need to check the array bounds in the inner
     *    match count increment loop.
 dbString = database - 1;
 aTable = theStore->alphaTable;
 aList = theStore->alphaList;
 threshold = fragSize-diffsAllowed;

 numMatch = 0;
 count = -fragSize;// count = current database loc.
 while( (dbChar = (long)(*(++dbString))) > 0x00 )
    // circular queue reset to center
 if( matchCur == matchTop )
 matchCur += fragSize;
    // check for a match to the fragment
 if((*matchCur+*(matchCur+fragSize)) >= threshold )
 matchPosition[ numMatch ] = count;
    // clear both old counts
 *matchCur = 0;
 *(matchCur+fragSize) = 0;

    // increment match counts for all possible
    //     fragment alignments
 hitOffset = aList + *(aTable + dbChar) - 1;
 while( (hitPos = (long)(*(++hitOffset))) >= 0 )
 *(matchCur + hitPos ) += 1;
    // The match count queue is walked in reverse
    //     order through memory because the alphaList
    //     indexes are positive.
     * Check the remaining match count entries for
     *    any fragments that extend beyond the end of
     *    the database.
 for( loop=0; loop < diffsAllowed; loop++)
 if( matchCur == matchTop )
 matchCur += fragSize;
 if((*matchCur+*(matchCur+fragSize)) >= threshold )
 matchPosition[ numMatch ] = count;
    // end of DNA_Match.c


Community Search:
MacTech Search:

Software Updates via MacUpdate

Google Earth - View and contr...
Google Earth gives you a wealth of imagery and geographic information. Explore destinations like Maui and Paris, or browse content from Wikipedia, National Geographic, and more. Google Earth combines... Read more
ClamXav 2.10 - Virus checker based on Cl...
ClamXav is a popular virus checker for OS X. I have been working on ClamXav for more than 10 years now, and over those years, I have invested a huge amount of my own time and energy into bringing... Read more
Tweetbot 2.4.4 - Popular Twitter client.
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Sierra Cache Cleaner 11.0.1 - Clear cach...
Sierra Cache Cleaner is an award-winning general purpose tool for macOS X. SCC makes system maintenance simple with an easy point-and-click interface to many macOS X functions. Novice and expert... Read more
Things 2.8.8 - Elegant personal task man...
Things is a task management solution that helps to organize your tasks in an elegant and intuitive way. Things combines powerful features with simplicity through the use of tags and its intelligent... Read more
Remotix 4.1 - Access all your computers...
Remotix is a fast and powerful application to easily access multiple Macs (and PCs) from your own Mac. Features Complete Apple Screen Sharing support - including Mac OS X login, clipboard... Read more
Airfoil 5.1.2 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
Firefox 49.0.1 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
Default Folder X 5.0.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click on... Read more
Safari Technology Preview 10.1 - The new...
Safari Technology Preview contains the most recent additions and improvements to WebKit and the latest advances in Safari web technologies. And once installed, you will receive notifications of... Read more

4 games like Burly Men at Sea to inspire...
Burly Men at Sea is out today and it looks a treat. It tells the tale of three Scandinavian fishermen who leave the humdrum of their daily lives to go exploring. It’s a beautiful folksy story that unfurls as you interact with the environment... | Read more »
3 reasons you need to play Kingdom: New...
Developed by a tag team of indie developers - Thomas "Noio" van den Berg and Marco "Licorice" Bancale - Kingdom is a vibrant medieval fantasy adventure that casts players as a king or queen who must expand their empire by exploring the vasts lands... | Read more »
JoyCity have launched a brand new King o...
Great news for all of you Game of Dice fans out there - JoyCity have just released a brand new limited edition pack with a really cool twist. The premise of Game of Dice is fairly straightforward, asking you to roll dice to navigate your way around... | Read more »
Burly Men at Sea (Games)
Burly Men at Sea 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Burly Men at Sea is a folktale about a trio of large, bearded fishermen who step away from the ordinary to seek adventure. | Read more »
3 tips for catching the gnarliest waves...
Like a wave breaking on the shore, Tidal Rider swept its way onto the App Store charts this week settling firmly in the top 10. It’s a one-touch high score-chaser in which you pull surfing stunts while dodging seagulls and collecting coins. The... | Read more »
The beginner's guide to destroying...
Age of Heroes: Conquest is 5th Planet Games’ all new turn-based multiplayer RPG, full of fantasy exploration, guild building, and treasure hunting. It’s pretty user-friendly as far as these games go, but when you really get down to it, you’ll find... | Read more »
Infinite Tanks (Games)
Infinite Tanks 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: | Read more »
Agatha Christie - The ABC Murders (FULL)...
Agatha Christie - The ABC Murders (FULL) 1.0 Device: iOS Universal Category: Games Price: $6.99, Version: 1.0 (iTunes) Description: Agatha Christie: The ABC Murders Your weapon is your knowledge. Your wits will be put to the ultimate... | Read more »
HeadlessD (Games)
HeadlessD 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: HeadlessD is hand-painted dungeon crawler with intuitive touch controls and NO in-app purchases. | Read more »
Leaf for Twitter (Social Networking)
Leaf for Twitter 1.0.1 Device: iOS iPhone Category: Social Networking Price: $4.99, Version: 1.0.1 (iTunes) Description: | Read more »

Price Scanner via

Apple refurbished 2015 13-inch MacBook Airs a...
Apple has Certified Refurbished 2015 13″ MacBook Airs available starting at $759. An Apple one-year warranty is included with each MacBook, and shipping is free: - 2015 13″ 1.6GHz/4GB/128GB MacBook... Read more
MacBook Airs on sale for up to $100 off MSRP
B&H Photo has 13″ and 11″ MacBook Airs on sale for up to $100 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 11″ 1.6GHz/128GB MacBook Air: $799 $100 MSRP - 11″ 1.6GHz/256GB... Read more
Apple refurbished 12-inch 128GB iPad Pros ava...
Apple has Certified Refurbished 12″ Apple iPad Pros available for up to $160 off the cost of new iPads. An Apple one-year warranty is included with each model, and shipping is free: - 32GB 12″ iPad... Read more
Phone2Action Unveils New Voter Turnout Techno...
Phone2Action, a leading digital advocacy platform, today launched its Tech to Vote Civic Action Center digital advocacy and communications platform on National Voter Registration Day September 27.... Read more
Apple & Deloitte Team Up to Help Business...
Apple and international professional services firm Deloitte have announced a partnership to help companies quickly and easily transform their workflow dynamics by maximizing the power, ease-of-use,... Read more
Chop Commute – See Traffic and Drive Times on...
Shrewsbury, Massachusetts based Indie developer, InchWest has released Chop Commute 1.61, a Mac app that takes the guesswork out of daily commute by showing real-time traffic and drive times right on... Read more
12-inch 32GB WiFi iPad Pros on sale for $50 o...
B&H Photo has 12″ 32GB WiFi Apple iPad Pros on sale for $50 off MSRP, each including free shipping. B&H charges sales tax in NY only: - 12″ Space Gray 32GB WiFi iPad Pro: $749 $50 off MSRP -... Read more
Recent price drops on refurbished iPad minis...
Apple recently dropped prices on several Certified Refurbished iPad mini 4s and 2s as well as iPad Air 2s. An Apple one-year warranty is included with each model, and shipping is free: - 16GB iPad... Read more
Apple refurbished Mac minis available startin...
Apple has Certified Refurbished Mac minis available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz Mac mini: $419 $80 off MSRP - 2.6GHz Mac... Read more
13-inch 2.5GHz MacBook Pro available for $928...
Overstock has the 13″ 2.5GHz MacBook Pro available for $927.99 including free shipping. Their price is $171 off MSRP. Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
*Apple* Wireless Lead - T-ROC - The Retail O...
…wealth of knowledge in wireless sales and activations to the Beautiful and NEW APPLE Experience store within MACYS.. THIS role, APPLE Wireless Lead, isbrandnewas Read more
Lead *Apple* Advocate - T-ROC - The Retail...
…Company, is proud of its unprecedented relationship with our partner and client, APPLE ,in bringing amazing" APPLE ADVOCATES"to "non" Apple store locations. Read more
*Apple* Advocate - T-ROC - The Retail Outsou...
…Company, is proud of its unprecedented relationship with our partner and client, APPLE ,in bringing amazing" APPLE ADVOCATES"to "non" Apple store locations. Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.