TweetFollow Us on Twitter

Sep 97 Challenge

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

Programmer's Challenge

by Bob Boonstra, Westford, MA

Image Locator

Imagine yourself with a collection satellite images and the task of finding a particular item in those images. Rather than look for a needle in this image haystack manually, you might call on your PowerMac to narrow down the choices for you. We'll enlist the aid of our Programmer's Challenge participants to help you do that job quickly. The Challenge this month is to detect the presence of a target pattern inside a larger background image. Because the background has been detected by an imperfect sensor, there is noise present in the background image. Your code will need to detect the target in the background despite this noise.

The prototype for the code you should write is:

#define topLeft(r)    (((Point *) &(r))[0])

void InitTarget(
  BitMap pattern,    /* image to be detected */
  BitMap mask      /* bits in image that we care about */

long /* numFound */ ImageDetect(
  BitMap backgroundImage,  /* find the target image in backgroundImage */
  Point locations[],    /* return topLeft of matching locations here */
  long maxLocations,    /* max number of locations to return */
  float noise        /* allow this fraction of mismatched bits */

void CleanUp(void);  /* deallocate any memory allocated by InitTarget */

Image location will take place in two steps. First, your InitTarget routine will be called with the target pattern that you will be looking for. Next, the ImageDetect routine will be called multiple times with a different background image and an associated noise threshold. ImageDetect should locate all occurrences of the target in the background, allowing for mismatched bits up to the noise threshold, and return the location of the pattern matches. Finally, the CleanUp routine will be called to allow you to deallocate any memory allocated by InitTarget.

InitTarget will be called with two BitMaps that describe the target pattern to be detected. The pattern BitMap identifies bits that should be set to 1, and the mask BitMap describes the bits that you care about (1s and 0s). Any bits not in the mask are not part of the target image, and the corresponding values in the background image are to be ignored. InitTarget should process the target image as desired and allocate memory to remember it.

ImageDetect will then be called multiple times (5-10 on average for each call to InitTarget). You should locate each occurrence of the target image in backgroundImage and return the coordinate in the background of topLeft(pattern.bounds) in the locations array. The noise parameter describes the fraction of target bits where the backgroundImage is allowed to differ from the target and still be considered a match. Up to noise times the number of 1s in the mask, rounded down, bits may be mismatched. Normally, locations will be large enough to hold all of the matches found, but you should not return more than the maxLocations matches for which storage has been allocated. The pattern matches may be returned in any order. If the maxLocations limit is exceeded, the choice of which matches to report is yours. ImageDetect should return the number of matches found.

Other information: The bounds rectangle for the pattern and the mask will be identical. All bits set in the pattern will also be set in the mask (but not the converse). The backgroundImage will typically be the size of a large monitor (e.g., 1024x768, or 1600x1200).

This will be a native PowerPC Challenge, using the latest CodeWarrior environment. In keeping with tradition, September is assembly language month here at the Programmer's Challenge. Solutions may be coded in PowerPC or 68K assembly language, C, C++, or Pascal.

Finally, we should note that the Programmer's Challenge began its sixth year last month. During that time, the Challenge has changed development environments, moved from 68K to PowerPC, and expanded its selection of languages. We appreciate the participation of our readers, without which the Challenge would not be possible. Happy belated birthday, Programmer's Challenge.

Three Months Ago Winner

The June Challenge was to implement a Turing Machine, a finite state machine augmented with an infinite amount of external storage. Twenty people submitted entries, and 17 of those worked correctly. Congratulations to Ernst Munter (Kanata, Ontario) for submitting the fastest solution and returning to the Challenge winner's circle.

The key to success in this Challenge was being able to quickly find the rule that applied to the current machine state and the current input symbol. A variety of techniques were used to find the applicable rule. Hashing was used by many of the faster entries. Ernst uses either hashing or a simple lookup table, depending on memory availability. Others sorted the rules and used a binary search. The slower solutions typically used a brute force approach of simply searching linearly through the rule set.

I used two types of test cases to stress the solutions. The first case involved a Turing Machine of approximately 2300 rules that sorted an input tape with an alphabet of 30 symbols and tape lengths of about 100 symbols. This case required over 113,000 Turing Machine state changes. The second test case was a Universal Turing Machine. A UTM is an interesting creature. Its input tape has two parts, an encoded version of the rules (program) for another Turing Machine, which it is to execute, and the input tape for that emulated program. The tape also contains an area where the Universal TM maintains the state for the program being emulated. The UTM operates by looking up the rule (or program instruction) that applies given the current state of the machine being emulated, remembering that instruction while it moves to the current input for the emulated machine, and then executing that instruction. The Universal Turing Machine I used operated on a binary alphabet and consisted of 184 rules, operating on an input tape that described a simple unary addition machine. This test case required just under 240,000 state changes to execute.

The table below lists for each entry the execution times in milliseconds for the sort test case and the Universal Turing Machine case, total execution time, code and data sizes, and the programming language used. The number in parentheses after the entrant's name is the total number of Challenge points earned in all Challenges to date prior to this one.

NameTime1Time2Total TimeCodeDataLanguage
Ernst Munter (246) 28.1 29.3 57.6 920 8 C++
Russ Webb 30.9 33.0 64.2 1696 140 C
Devon Carew 33.4 35.6 79.5 976 28 C
Gary Beith (24) 39.6 39.9 86.9 592 32 C
Mason Thomas (4) 47.9 40.5 89.1 740 8 C
Kevin Cutts (57) 42.4 43.9 89.7 620 32 C++
Simon Holmes à Court 44.1 42.3 90.0 744 32 C++
Juerg Wullschleger 48.5 50.4 99.7 476 8 C
Daniel Harding 96.0 63.0 159.7 2612 406 C++
Zach Thompson 93.2 64.8 161.3 1076 48 C++
Gregory Cooper (54) 107.8 84.6 192.7 668 40 C
Graham Herrick 137.0 107.2 244.8 820 16 C
Andy Scheck (17) 3239.0 158.3 3397.0 212 8 C++
Charles Higgins (20) 3238.0 167.8 3406.0 276 8 C
David Whitney 4174.0 272.3 4449.0 19800 2745 C++
Bjorn Davidsson (6) 6565.0 165.6 6731.0 224 8 C++
Terry Noyes 6737.0 198.3 6936.0 200 8 C
R.B. 2736 99 C
S.A. 840 448 C
W.R. 1148 8 C++

Top 20 Contestants

Here are the Top 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, Ernst 196
2. Gregg, Xan 83
3. Cooper, Greg 54
4. Lengyel, Eric 40
5. Boring, Randy 37
6. Lewis, Peter 32
7. Mallett, Jeff 30
8. Murphy, ACC 30
9. Larsson, Gustav 27
10. Antoniewicz, Andy 24
11. Nicolle, Ludovic 21
12. Picao, Miguel Cruz 21
13. Brown, Jorg 20
14. Day, Mark 20
15. Gundrum, Eric 20
16. Higgins, Charles 20
17. Slezak, Ken 20
18. Studer, Thomas 20
19. Karsh, Bill 19
20. Nevard, John 19

Here is Ernst's winning solution:

Turing.cp ® 1997 Ernst Munter

Problem Statement
Implement the engine for a Turing Machine, a state machine which, at each step, reads a symbol from a tape, consults a rule which is a function of the current state and the symbol. The rule specifies a new state, a symbol to output, and the direction in which to move the tape, or to halt.
I first try to build a lookup table as an index into the rules array. But this may require an "unreasonable" amount of memory.

First, I scan the rules to determine the amount of table memory required for a simple lookup index. If this appears to be too much, I go to plan B: a hashed index.

The hash table uses linear open addressing: when the table is built and an index location is needed which is already in use we have a collision. To resolve it, I scan linearly through the index array until a free location is found. The size of the index array is larger than the number of rules, so a free location will always be found.

Optimization of hash table lookup
The majority of rules will hash to unique index addresses.

Rules which hash to the same value can be seen as a sequence of index table entries, with the primary location containing the first rule address to be found.

When the Turing Machine is executing, any colliding rule that is encountered will have its index moved to the primary index location, on the assumption that it will be used again, and will then be found more quickly.

A minimum amount of table memory of 8K entries is always provided. But for larger rule sets, an index table that will occupy about 1/2 to 3/4 the amount of memory taken by the rules array itself may be allocated.

The memory allocated for the simple lookup table will be the number_of_states * number_of_symbols, rounded up to a power of 2, but not more than 8K entries, or 2 * number_of_rules, whichever is larger.

If the memory required for the simple index would exceed those rules, for example if there are a lot of holes in the symbol/state space, the hashed index is used.

The memory allocated for the hash index array will be the larger of 8K entries or 2 * number_of_rules, rounded up to the nearest power of 2.

For example, a rule set of up to 2K rules may result in a 32K byte index; a rule set of 50,000 rules which occupy 1M of rules memory may get an index table of 512K bytes.

#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include "turing.h"

const enum {    // constants controlling min size of index
  MIN_BITS   = 13,
  MIN_SIZE    = 1L<<MIN_BITS };  
typedef const TMRule* TMRulePtr;

Boolean TuringMachine(
  const TMRule theRules[],
  ulong numRules,
  ulong *theTape,
  ulong tapeLen,
  long rwHeadPos,
  TMMoveProc ReportMove
)  {
  TMRulePtr* index;
  ulong    state=0;
  ulong    symbol;
  int    direction;
  ulong*  tape=theTape+rwHeadPos;
  ulong*  tapeEnd=theTape+tapeLen;

  ulong    mask;
  TMRulePtr rule=theRules;

// The function contains 2 very similar sections,
// one section uses a plain lookup table for an index,
// the other uses a hash table.

// Try to construct a collision-free index of rule addresses

// compute table size
  ulong   maxState=rule->oldState;
  ulong   maxSym=rule->inputSymbol;
  ulong   minSym=rule->inputSymbol;
  for (int i=1;i<numRules;i++) {
    if (maxState<rule->oldState) maxState=rule->oldState;
    if (maxSym<rule->inputSymbol) maxSym=rule->inputSymbol;
    if (minSym>rule->inputSymbol) minSym=rule->inputSymbol;
  ulong numSyms=maxSym-minSym+1;
  ulong numStates=maxState+1;
  ulong numIndex=(numStates)*(numSyms);

  if ((numIndex<numStates)               // overflow
    || ((numIndex > MIN_SIZE)
    && (numIndex > EXPANSION*numRules)))  // too large
      goto try_hash;

// increase size to the next power of 2
  ulong dummy=1;
  while (numIndex) {

// Allocate the table memory

// Always expect to get the memory, but just in case ...
  if (index==0)
    return FALSE;

// All unused index locations will remain 0

// Scan the rules and populate the index array
  for (int i=0;i<numRules;i++) {
    ulong addr=
      mask & (rule->oldState*numSyms+rule->inputSymbol);
// Using the collision-free index table:
// Loop until the tape halts or we fail on error
  do {
      ulong addr=mask & (state*numSyms+symbol);
      if (rule == 0)    // illegal symbol, no rule


      if (direction==kHalt) {
        return TRUE;  
  } while ((tape>=theTape) && (tape<tapeEnd));
  return FALSE;

// Section 2
// If we get here, we could not make a simple table
// and have to go with a hash table, collisions are possible

// Find table size >= minimum size
  while (numIndex < EXPANSION*numRules) {

// Allocate the table memory

// Always expect to get the memory, but just in case ...
  if (index==0)
    return FALSE;

// All unused index locations will remain 0

  ulong   hFactor=1 | (numIndex/numStates);
  long     hDelta=1 | (hFactor>>1);

// Scan the rules and populate the index array
  for (int i=0;i<numRules;i++) {
    ulong addr=
      mask & (rule->oldState*hFactor+rule->inputSymbol);

// if primary location is not empty: find next free location
    while (index[addr])   
      addr=mask & (addr+hDelta);

// Using the hash index table:
// Loop until the tape halts or we fail on error.
// This loop is the same as the loop in the first section
// except we have to check for possible collisions with each rule..
  do {
      ulong addr=mask & (state*hFactor+symbol);
      if (rule == 0)          // illegal symbol, no rule
// check if we have the right rule, or a collision  
    if ((symbol != rule->inputSymbol)
      || (state != rule->oldState)) {  
       const TMRule* rule0=rule;
        ulong addr0=addr;

      do {          // resolve the collision
        addr=mask & (addr+hDelta);
          if (rule == 0) {      // could not find rule
      return FALSE;
      } while ((symbol != rule->inputSymbol)
      || (state != rule->oldState));
      index[addr]=rule0;        // move last-used rule
      index[addr0]=rule;        // up in chain
// now we have the correct rule  


      if (direction==kHalt) {    // normal stop
        return TRUE;  

  } while ((tape>=theTape) && (tape<tapeEnd));

  return FALSE;

Community Search:
MacTech Search:

Software Updates via MacUpdate

Microsoft Remote Desktop 8.0.16 - Connec...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more
Spotify - Stream music, create...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
djay Pro 1.1 - Transform your Mac into a...
djay Pro provides a complete toolkit for performing DJs. Its unique modern interface is built around a sophisticated integration with iTunes and Spotify, giving you instant access to millions of... Read more
Vivaldi - Lightweight browser...
Vivaldi browser. In 1994, two programmers started working on a web browser. Our idea was to make a really fast browser, capable of running on limited hardware, keeping in mind that users are... Read more
Stacks 2.6.11 - New way to create pages...
Stacks is a new way to create pages in RapidWeaver. It's a plugin designed to combine drag-and-drop simplicity with the power of fluid layout. Features: Fluid Layout: Stacks lets you build pages... Read more
xScope 4.1.3 - Onscreen graphic measurem...
xScope is powerful set of tools that are ideal for measuring, inspecting, and testing on-screen graphics and layouts. Its tools float above your desktop windows and can be accessed via a toolbar,... Read more
Cyberduck 4.7 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Labels & Addresses 1.7 - Powerful la...
Labels & Addresses is a home and office tool for printing all sorts of labels, envelopes, inventory labels, and price tags. Merge-printing capability makes the program a great tool for holiday... Read more
teleport 1.2.1 - Use one mouse/keyboard...
teleport is a simple utility to let you use one single mouse and keyboard to control several of your Macs. Simply reach the edge of your screen, and your mouse teleports to your other Mac! The... Read more
Apple iMovie 10.0.8 - Edit personal vide...
With an all-new design, Apple iMovie lets you enjoy your videos like never before. Browse your clips more easily, instantly share your favorite moments, and create beautiful HD movies and Hollywood-... Read more

Use Batting Average and the Apple Watch...
Batting Average, by Pixolini, is designed to help you manage your statistics. Every time you go to bat, you can use your Apple Watch to track  your swings, strikes, and hits. [Read more] | Read more »
Celebrate Studio Pango's 3rd Annive...
It is time to party, Pangoland pals! Studio Pango is celebrating their 3rd birthday and their gift to you is a new update to Pangoland. [Read more] | Read more »
Become the World's Most Important D...
Must Deliver, by cherrypick games, is a top-down endless-runner witha healthy dose of the living dead. [Read more] | Read more »
SoundHound + LiveLyrics is Making its De...
SoundHound Inc. has announced that SoundHound + LiveLyrics, will be one of the first third-party apps to hit the Apple Watch. With  SoundHound you'll be able to tap on your watch and have the app recognize the music you are listening to, then have... | Read more »
Adobe Joins the Apple Watch Lineup With...
A whole tidal wave of apps are headed for the Apple Watch, and Adobe has joined in with 3 new ways to enhance your creativity and collaborate with others. The watch apps pair with iPad/iPhone apps to give you total control over your Adobe projects... | Read more »
Z Steel Soldiers, Sequel to Kavcom'...
Kavcom has released Z Steel Soldiers, which continues the story of the comedic RTS originally created by the Bitmap Brothers. [Read more] | Read more »
Seene Lets You Create 3D Images With You...
Seene, by Obvious Engineering, is a 3D capture app that's meant to allow you to create visually stunning 3D images with a tap of your finger, and then share them as a 3D photo, video or gif. [Read more] | Read more »
Lost Within - Tips, Tricks, and Strategi...
Have you just downloaded Lost Within and are you in need of a guiding hand? While it’s not the toughest of games out there you might still want some helpful tips to get you started. [Read more] | Read more »
Entertain Your Pet With Your Watch With...
The Petcube Camera is a device that lets you use live video to check in on your pet, talk to them, and play with them using a laser pointer - all while you're away. And the Petcube app is coming to the Apple Watch, so you'll be able to hang out with... | Read more »
Now You Can Manage Your Line2 Calls With...
You'll be able to get your Line2 cloud phone service on the Apple Watch very soon. The watch app can send and receive messages using hands-free voice dictation, or by selecting from a list of provided responses. [Read more] | Read more »

Price Scanner via

Intel Compute Stick: A New Mini-Computing For...
The Intel Compute Stick, a new pocket-sized computer based on a quad-core Intel Atom processor running Windows 8.1 with Bing, is available now through Intel Authorized Dealers across much of the... Read more
Heal to Launch First One-Touch House Call Doc...
Santa Monica, California based Heal, a pioneer in on-demand personal health care services — will offer the first one-touch, on-demand house call doctor app for the Apple Watch. Heal’s Watch app,... Read more
Mac Notebooks: Avoiding MagSafe Power Adapter...
Apple Support says proper usage, care, and maintenance of Your Mac notebook’s MagSafe power adapter can substantially increase the the adapter’s service life. Of course, MagSafe itself is an Apple... Read more
12″ Retina MacBook In Shootout With Air And P...
BareFeats’ rob-ART morgan has posted another comparison of the 12″ MacBook with other Mac laptops, noting that the general goodness of all Mac laptops can make which one to purchase a tough decision... Read more
FileMaker Go for iPad and iPhone: Over 1.5 Mi...
FileMaker has announced that its FileMaker Go for iPad and iPhone app has surpassed 1.5 million downloads from the iTunes App Store. The milestone confirms the continued popularity of the FileMaker... Read more
Sale! 13-inch 2.7GHz Retina MacBook Pro for $...
 Best Buy has the new 2015 13″ 2.7GHz/128GB Retina MacBook Pro on sale for $1099 – $200 off MSRP. Choose free shipping or free local store pickup (if available). Price for online orders only, in-... Read more
Minimalist MacBook Confirms Death of Steve Jo...
ReadWrite’s Adriana Lee has posted a eulogy for the “Digital Hub” concept Steve Jobs first proposed back in 2001, declaring the new 12-inch MacBook with its single, over-subscribed USB-C port to be... Read more
13-inch 2.7GHz Retina MacBook Pro for $1234 w...
Adorama has the 13″ 2.7GHz/128GB Retina MacBook Pro in stock for $1234.99 ($65 off MSRP) including free shipping plus a free LG external DVD/CD optical drive. Adorama charges sales tax in NY & NJ... Read more
13-inch 2.5GHz MacBook Pro available for $999...
 Adorama has the 13-inch 2.5GHz MacBook Pro on sale for $999 including free shipping plus NY & NJ sales tax only. Their price is $100 off MSRP. Read more
Save up to $600 with Apple refurbished Mac Pr...
The Apple Store is offering Apple Certified Refurbished Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... 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
*Apple* Support Technician IV - Jack Henry a...
Job Description Jack Henry & Associates is seeking an Apple Support Technician. This position while acting independently, ensures the proper day-to-day control of Read more
*Apple* Client Systems Solution Specialist -...
…drive revenue and profit in assigned sales segment and/or region specific to the Apple brand and product sets. This person will work directly with CDW Account Managers Read more
*Apple* Software Support - Casper (Can work...
…experience . Full knowledge of Mac OS X and prior . Mac OSX / Server . Apple Remote Desktop . Process Documentation . Ability to prioritize multiple tasks in a fast pace Read more
*Apple* Software Support - Xerox Corporation...
…Imaging experience Full knowledge of Mac OS X and prior Mac OSX / Server Apple Remote Desktop Process Documentation Ability to prioritize multiple tasks in a fast pace Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.