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

BeSort

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 {

public:
 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

TOP 20 CONTESTANTS

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.

RankNamePoints
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:

DNA_Match.c

© 1996 Andy Antoniewicz

/* 
Problem:
DNA string match with wildcard & constant distance

Notes:
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.
 ********* ********* ********* ********* ********* ********/

InitMatch
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.
 * 
 ********* ********* ********* ********* ********* ********/

BuildAlphaList
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
 count++;
 }
 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);
 count++;
 }
 *(alphaList+count) = kEndOfAlphaList;
 count++;
 }
 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.
 * 
 ********* ********* ********* ********* ********* ********/

FindMatch
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;
 
 theStore->usedStorage
 = (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;
 numMatch++;
 }
 
    // 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.
 matchCur-;
 count++;
 }
 
    /*********
     * 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;
 numMatch++;
 }
 matchCur-;
 count++; 
 }
 
 return(numMatch);
 }
 
    // end of DNA_Match.c

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.