TweetFollow Us on Twitter

May 96 Challenge
Volume Number:12
Issue Number:5
Column Tag:Programmer’s Challenge

Programmer’s Challenge

By Bob Boonstra, Westford, Massachusetts

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Edge Detector

This month’s Challenge is to write a small image-processing application that scans a color image and identifies the boundaries of possible objects in that image. Applications for such a program might include image enhancement, special effects, or pattern recognition, although those applications would use a more sophisticated approach for detecting edges than we will be implementing for this Challenge.

The prototype for the code you should write is:

typedef enum {
 redOnly=1, greenOnly, redAndGreen, blueOnly,
 redAndBlue, greenAndBlue, redGreenAndBlue
} EdgeType;

void EdgeDetect(
 PixMapHandle pMapH, /* find edges in this PixMap */
 BitMap *bMap,   /* store edges in this BitMap */
 unsigned short threshold,/* color separations >= dist create an edge */
 EdgeType eType  /* which color components to look at */
);

Each pixel in the PixMap should be compared to the eight (or fewer) adjacent pixels differing in position by up to one row or column. If the pixel color is sufficiently different (as defined below) from any of the adjacent pixels, then the bit in the BitMap corresponding to that pixel should be set to 1. Otherwise, the BitMap bit should be set to 0. Obviously, pixels located in the first and last row and column will have fewer than eight adjacent pixels.

Whether two pixels differ by enough to constitute an edge is determined by comparing their rgb values. The distance between two pixels is the root-mean-square difference between the color components of their rgb values, considering only those components specified in the input EdgeType. For example, if the EdgeType is greenOnly, then the distance between two pixels is the absolute value of the difference in the green components of their colors. If the EdgeType is redGreenAndBlue, then the distance is the square root of the sum of the squares of the differences of the red components, the green components, and the blue components.

As a specific example, suppose we have two pixels with (red, green, blue) values of (0x1000, 0x2000, 0x4000) and (0x2000, 0x5000, 0xB000). The distance between these two pixels is:

 redOnly: 0x1000
 redAndGreen:    0x3298=sqrt(0x01000000+0x09000000)
 redGreenAndBlue:0x7AE5=sqrt(0x01000000+0x09000000+0x31000000)

Two pixels define an edge if their distance is greater than or equal to the threshold parameter. The threshold parameter is deliberately declared to be an unsigned short, even though pixels can differ by a greater amount. Since the definition of distance is symmetric, the bits corresponding to both edge pixels would be set in the BitMap.

The BitMap will be allocated and initialized for you by the calling routine. The storage pointed to by the BitMap baseAddr will also be allocated and initialized to zero. The bounds rectangles will be the same for the BitMap and the PixMap. Your code needs to deal with pixelSize values of 8, 16, or 32, with each case being equally weighted in the scoring. For PixMaps with indexed pixels, you will obviously need to look at the color table to find the rgb value corresponding to a given index. In the 16-bit case, you should follow the rules for converting a 5-bit color component into an 8-bit RGBColor component value (i.e., replicating the 3 most significant bits and appending them to constitute the least significant bits of the 8-bit component).

This will be a native PowerPC Challenge, scored using the latest Metrowerks C compiler. (No C++ or Pascal this month.)

Entries Due Ten Days Earlier

Although two issues may seem like a long time to wait for the results of the Challenge, it has always been a challenge (no pun intended) to complete the scoring of results in time for publication two issues later. We have been searching for a way to allow a little more time for evaluating the entries and writing the column without introducing any additional delay between publication of the problem and publication of the solution. The Challenge mailing list has allowed us to deliver the Challenge to readers on a predictable schedule wherever they live, regardless of variations in mailing dates. We are going to use the mailing list to advance the due date for Challenge solutions, without reducing the amount of time available for solving the Challenge. Starting with this month’s contest, Challenge entries will be due earlier, on the 1st of the month printed on the front cover. We will mail the problem to the mailing list on the 12th of the preceding month, also about ten days earlier than before.

If you are not already a member of the Challenge mailing list, you can join the ~300 subscribers from 25 countries already on the list by sending email to macjordomo@listmail.xplain.com with the line “sub challenge-A YourName” in the body.

Two Months Ago Winner

The response to the Words the Reverse Challenge was overwhelming. I don’t know if it was due to allowing C++ and Pascal entries, or to the relative simplicity of the problem, but I received a record 45 entries to this Challenge. The Challenge was to write code that would reverse the order of words in a block of input text while preserving intervening white space and special characters, and adjusting capitalization of the reversed words to match that of corresponding input words. It is appropriate that the first Challenge admitting Pascal solutions was won by a well-known proponent of Pascal (see MacTech Magazine 12.4 [April 1996] 70, and p.20 of this issue). Congratulations to Peter Lewis (Perth, Australia), author of Anarchie, NetPresenz, ObiWan, and other shareware products, for submitting the fastest entry to the Words The Reverse Challenge.

The test cases included a number of short, untimed strings designed to verify correctness. To my surprise, more than one-third of the entries failed these tests (or crashed outright). People had problems with strings that contained a single word, with strings that began with punctuation, with words of a single letter, and with the middle word in strings that contained an odd number of words. Remember, correctness is the first requirement for your solution.

For the timing tests, I ran a set of cases averaging around 40,000 words per case, totaling upwards of 500,000 words and 3 million characters for all cases. I eliminated from the input any “words” that started with a digit, because the problem statement was silent on how to deal with capitalization in that case. A number of people, including the winner, chose to treat words starting with digits as capitalization-neutral, so that the word being exchanged with the digit-word retained its original capitalization. This was a very reasonable approach (and I wish I had included it in the problem statement), but since the problem was silent, the fairest thing to do was to eliminate this condition from the test data.

The experiment allowing multiple languages and compilers went reasonably well. Most people, as requested, either provided a project/make file to link their solution with C code, or specifically indicated which compiler they wanted me to use. For those C entries that did not indicate a preference, I used the Metrowerks C compiler. A few people submitted solutions for environments that either did not generate native PowerPC code (e.g., non-SPM THINK C) or did not link with C code (e.g., THINK Pascal). For those entries, I mapped them to the closest possible environment (SPM C and Metrowerks Pascal, in these two cases).

Here are the times, compiler selection, code size, and data size for the correct solutions. Numbers in parentheses are the cumulative point total for all previous Challenges, not including this one.

Nametimecompilercodedata
Peter N Lewis (10)525MW Pascal89642
Ludovic Nicolle (4)602MW C12408
Kevin M. Cutts (50)607MW C65620
Gary Beith (20)626MW C20888
Ernst Munter (132)630MW C680560
Robert Marsa650MW C55259
Eric Lengyel (40)669MW C368140
John Nevard (17)670MW C56420
Wolfgang Thaller (4)681MW C61620
Randy Boring687MW C10432024
Bill Karsh (80)695MW C11288
Kirill Medvinsky703MW C++54012
Mark Bassam Salem705MW C++59232
Tom Saxton (10)710MW C360422
Karl Anderson716MW C604536
Lars Farm762MW C++90470
David McLeod842MW C5001315
Erik Sea884MW C760532
Robert Leslie/Geoff Hulten938MW C436268
Björn Davidsson (4)1122MW C++102020
Tom Stone1180SPM C75216
Gustav Larsson (87)1270MW C784536
Ryan Gronlie1294MW C44420
Michael White1397MW C1924130
Rishi Khan1447MW C9608
Richard Fattic1576MW C9088
Stefan C. Sinclair1668SPM MrC124840
David Newport2420SPM C78416
Ken Slezak (10)2468SPM C80816

To help understand why the single correct Pascal entry was faster than all of the C entries, I hand-translated the winning Pascal code into C, compiled it with several C compilers, and compared the results. I turned on all speed optimizations in each case, and optimized for the 604 processor when the compiler supported that option. Since conventional wisdom is that C is more efficient than Pascal, I expected to find that the winning algorithm would be faster in C than it was in Pascal. In fact, the results for two of the C compilers were essentially the same as the Pascal results, and one was measurably worse (for reasons that I did not have time to investigate). Here are the results of my test:

Environment / Languageexecution timecode size
Metrowerks / Pascal525896
Metrowerks / C533868
SPM / Symantec C536712
SPM / MrC6111992

Top 20 Contestants of All Time

Here are the Top Contestants for the Programmer’s Challenges to date, including everyone who has accumulated more than 20 points. The numbers below include points awarded for this month’s entrants.

RankNamePoints
1.[Name deleted]176
2.Munter, Ernst134
3.Gregg, Xan92
4.Larsson, Gustav87
5.Karsh, Bill80
6.Stenger, Allen65
7.Cutts, Kevin57
8.Riha, Stepan51
9.Goebel, James49
10.Nepsund, Ronald47
11.Mallett, Jeff44
12.Kasparian, Raffi42
13.Vineyard, Jeremy42
14.Lengyel, Eric40
15.Darrah, Dave31
16.Brown, Jorg30
17.Lewis, Peter30
18.Landry, Larry29
19.Beith, Gary24
20.Elwertowski, Tom24
21.Lee, Johnny22
22.Noll, Robert22

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:

points to win table:

1st place20 points5th place2 points
2nd place10 pointsfinding bug2 points
3rd place7 pointssuggesting Challenge2 points
4th place4 points

Peter’s solution is relatively straightforward, and he hints in the preamble that he might have done better if he had spent more time on it. One tip that you might glean from Peter’s code is the way he allocates dynamic memory. First, he deals with small problems with memory allocated on the stack. Second, he uses NewHandle rather than NewPtr to allocate dynamic memory. NewHandle is faster than NewPtr, because NewPtr may move relocatable blocks around before doing the allocation to avoid fragmenting the heap. Peter also locks the handle before using it, which is always safe, but is not necessary unless your code does something that moves memory. Whether locking is necessary in this case depends on whether you believe the documentation that says BlockMove doesn’t move memory. Here is Peter’s winning solution:

Challenge.p

Peter N Lewis, peter@stairways.com.au

unit Challenge;

interface

 uses
 Types;
 
 type
 CharsArray = packed array[0..0] of byte;
 CharsArrayPtr = ^CharsArray;
 
 procedure ReverseTheWords( 
    text: CharsArrayPtr; 
    numCharsIn: longint );

implementation

 uses
 Memory;

{
    This is not really optimal, I felt compelled to send in a Pascal solution since I was
    one of the people who complained about the language bias.  I didn’t have time to 
    do this challenge justice.
    
    Method:
    *     Allocate a block of memory equal in size to numCharsIn (if numCharsIn < 2048, 
    we short circuit this to use a block of memory on the stack).
    *     Initialize a 0..255 array to determine whether a character is  an alphanum (I 
    could just use the ANSI ctype.p file, but without a macro call, there is a pretty 
    big hit).
    *     reverse the words from the source to our new buffer.  We move in from both
    ends,  copying non-alphanums, and then swapping words and fixing the case.
    *     BlockMoveData the buffer back to the source buffer.
    *     Release the memory if we allocated any.
}

 procedure ReverseTheWords( 
      text: CharsArrayPtr; 
      numCharsIn: longint );
 const
 stack_space_size = 2048;
 var
 space: packed array[0..stack_space_size] of byte;
 buffer: CharsArrayPtr;
 memory: Handle;
 leftin, leftout, rightin, rightout, leftedge, 
 rightedge: longint;
 i: longint;
 leftchar, rightchar: integer;
 alphanum_set:array[0..255] of Boolean;
 begin
    { allocate memory if needed }
 if numCharsIn < stack_space_size then begin
 memory := nil;
 buffer := @space;
 end else begin
 memory := NewHandle( numCharsIn );
 if memory = nil then begin
 DebugStr( 'Memory allocation failed!' );
 exit( ReverseTheWords );
 end;
 HLock(memory);
 buffer := CharsArrayPtr( memory^ );
 end;
 
    { init - I wish I could do this at compile time - Turbo Pascal can }
 for i := 0 to 255 do alphanum_set[i] := false;
 for i := 48 to 57 do alphanum_set[i] := true; { 0..9 }
 for i := 65 to 90 do alphanum_set[i] := true; { A..Z }
 for i := 97 to 122 do alphanum_set[i] := true; { a..z }

    { reverse }
 leftin := 0;
 leftout := leftin;
 rightin := numCharsIn - 1;
 rightout := rightin;
 while leftin <= rightin do begin
 while not alphanum_set[text^[leftin]] & (leftin <= rightin) 
                                                do begin
 buffer^[leftout] := text^[leftin];
 Inc(leftout);
 Inc(leftin);
 end;
 while not alphanum_set[text^[rightin]] & (leftin < rightin) 
                                                do begin
 buffer^[rightout] := text^[rightin];
 Dec(rightout);
 Dec(rightin);
 end;
 leftedge := leftin;
 rightedge := rightin;
 while alphanum_set[text^[leftin]] & (leftin <= rightin) 
                                                do begin
 Inc(leftin);
 end;
 if leftin > rightin then begin { central word, just copy, ignore case }
 for i := leftedge to leftin - 1 do begin
 buffer^[leftout] := text^[i];
 Inc(leftout);
 end;
 end else begin
 while alphanum_set[text^[rightin]] do begin 
    { there is a sentinel now, we dont need to check leftin < rightin }
 Dec(rightin);
 end;
 leftchar := text^[leftedge];
 rightchar := text^[rightin+1];
 if ( leftchar > 57 ) & ( rightchar > 57 ) then begin 
    { both letters }
 if leftchar > 90 then begin
 if rightchar <= 90 then begin
 rightchar := rightchar + $20;
 leftchar := leftchar - $20;
 end;
 end else begin
 if rightchar > 90 then begin
 rightchar := rightchar - $20;
 leftchar := leftchar + $20;
 end;
 end;
 end;
 buffer^[leftout] := rightchar;
 Inc(leftout);
 for i := rightin+2 to rightedge do begin
 buffer^[leftout] := text^[i];
 Inc(leftout);
 end;
 for i := leftin-1 downto leftedge+1 do begin
 buffer^[rightout] := text^[i];
 Dec(rightout);
 end;
 buffer^[rightout] := leftchar;
 Dec(rightout);
 end;
 end;
 
    { copy buffer }
 BlockMoveData( buffer, text, numCharsIn );
 
    { free memory if required }
 if memory <> nil then begin
 DisposeHandle( memory );
 end;
 end;
 
end.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.