TweetFollow Us on Twitter

Mar 95 Challenge
Volume Number:11
Issue Number:3
Column Tag:Programmer’s Challenge

Programmer’s Challenge

By Mike Scanlin, Mountain View, CA

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

Method Dispatcher

One of the main reasons why I don’t like object oriented languages is because of the inefficiencies the language usually introduces on the runtime code. If you’ve ever traced through a method dispatch routine then you know what I mean (what ever happened to the days of simple, direct JSR’s?). This month you have a chance to write a fast method dispatcher. Who knows? If it’s efficient enough I might just toss my assembler and use your dispatcher with a high level language instead...

The prototype of the function you write is:

typedef unsigned short ushort;
typedef ushort ClassID;
typedef ushort MethodNumber;

MethodAddress
FindMethod(theClassID, theMethodNumber)
ClassID theClassID;
MethodNumbertheMethodNumber;

TheMethodNumber is the number of the method you’re trying to find the address of and theClassID is the ID of the class you want it for. You’ll pass theClassID to a function called GetClassPtr to get a pointer to a Class data structure, which looks like this:

typedef void *MethodAddress;

typedef struct {
 MethodNumber  methodNumber;
 MethodAddress methodAddress;
} MethodEntry;

typedef struct {
 ushort inheritedCount;
 ushort inheritedClasses[15];
 MethodNumber  largestMethodNumber;
 ushort methodCount;
 MethodEntrymethods[];
} Class, *ClassPtr;

The function GetClassPtr will be part of my test bench, although you’ll have to implement at least a rudimentary version of it to test your program (or you can e-mail me for a sample version):

ClassPtr
GetClassPtr(classID)
unsigned short classID;

If GetClassPtr returns -1 (kClassNotFound) then the class cannot be found and your FindMethod routine should return 0 (kMethodNotFound). I will be providing sample data and a sample GetClassPtr function for those who are interested. To get a copy, send me e-mail at scanlin@genmagic.com (internet) or any of the Programmer Challenge addresses listed on page 2.

Once you have a ClassPtr you should look in that class’s methods[] array to see if you can find an entry whose methodNumber is equal to theMethodNumber. Methods[] is a variable-length array (thus, making Class a variable-size structure) containing methodCount number of entries which are sorted smallest to largest by methodNumber. MethodCount is 1-based and is always greater than zero. If you find a match then you should return the corresponding methodAddress.

If you don’t find a match then you should look at the inherited classes (starting with index zero) to see if the method is implemented by one of this class’s superclasses. We support multiple inheritance here and the number of classes we inherit from is stored in inheritedCount (which will be from zero to 15). The class IDs of the classes we inherit from are stored in the inheritedClasses[ ] array. You can pass any of the entries in inheritedClasses to GetClassPtr to get a ClassPtr to that class.

If you can’t find the requested methodNumber in any part of the inheritance tree then FindMethod should return zero (kMethodNotFound).

Here’s a simple example. These 54 bytes (starting at location 0x1000) represent class ID 5:

1000:00000000 00000000 00000000 00000000 
1010:00000000 00000000 00000000 00000000 
1020:00680003 0023AAAA AAAA0057 BBBBBBBB 
1030:0068CCCC CCCC 

The short at location 1000 (inheritedCount) tells us that there are no inherited classes for this class. The short at location 1022 (methodCount) tells us that this class has 3 methods. Methods[0] is from 1024 to 1029; the methodNumber is 23 and the methodAddress is AAAAAAAA (this is just test data to illustrate the structure). Methods[1] is from 102A to 102F and methods[2] is from 1030 to 1035. The short at location 1020 (largestMethodNumber) is equal to the methodNumber of the last MethodEntry in the list (which is the largest methodNumber overall since the list is sorted). In other words, the expression theClassPtr->largestMethodNumber == theClassPtr-> methods[theClassPtr->methodCount-1].methodNumber is always true.

If this class had inherited from class 7 and class 9 then it would have looked like this instead:

1000:00020007 00090000 00000000 00000000 
1010:00000000 00000000 00000000 00000000 
1020:00680003 0023AAAA AAAA0057 BBBBBBBB 
1030:0068CCCC CCCC 

In either case, if you call GetClassPtr(5), since this is class 5 we’re looking at, you would have the value 0x1000 (as type ClassPtr) returned to you.

Since I’ll be calling FindMethod several thousand times with the same set of classes (just like a real runtime system!) you’ll probably want to implement some kind of cache. And since it is desirable for runtime systems to take as little memory as possible, we’re going to have a rule that says your code cannot use more than 16K of memory for its cache (use a static to keep a pointer to it). The total number of methods in the set of classes I’ll be testing with is about 5000, numbered from 1 to 5000. The total number of classes is about 400, numbered from 1 to 400. Those 400 classes will implement an average of 15 methods each and will inherit from an average of 5 other classes (that’s 5 total, once you’ve walked the entire inheritance tree for a particular class). Of course, some methods will be called frequently while others are hardly ever called.

Because this is a little complex, I’m going to give you the brute force way of doing what I’ve described. I’m sure you can do better than this (I’ve used short variable names so that the code will fit in the magazine column):

MethodAddress
FindMethod(cid, mn)
ClassID cid;
MethodNumbermn;
{
 ClassPtr cp;
 MethodAddress addr;
 int    i;
 
 cp = GetClassPtr(cid);
 if (cp == kClassNotFound)
 return kMethodNotFound;
 
 /* look in this class */
 i = 0;
 do {
 if (mn == cp->methods[i].methodNumber)
 return cp->methods[i].methodAddress;
 i++;
 } while (i < cp->methodCount);
 
 /* look in superclasses */
 i = 0;
 while (i < cp->inheritedCount) {
 addr = FindMethod( cp->inheritedClasses[i], mn);
 if (addr != kMethodNotFound)
 return addr;
 i++;
 }
 return kMethodNotFound;
}

E-mail me if you have any questions or if you want the sample data and GetClassPtr function. And if you want to see your name in print all you have to do is either enter a challenge or have me use one of your suggested challenges.

Two Months Ago Winner

Congratulations to Kevin Cutts (Schaumburg, IL) for winning the Poker Hand Evaluator Challenge. And kudos to Gustav Larsson (Mountain View, CA) for being 60% smaller and only about 4% slower than Kevin.

Here are the times and code sizes for each entry. Numbers in parens after a person’s name indicate how many times that person has finished in the top 5 places of all previous Programmer Challenges, not including this one:

Name time code

Kevin Cutts (3) 317 6022

Gustav Larsson 331 2656

Jeff Mallett (3) 331 9428

Ernst Munter (5) 457 2516

Dave Darrah (1) 749 2996

Raffi Kasparian (1) 1230 7394

Kevin wrote four different versions of his BestHand routine; one for every combination of the Booleans wildCardAllowed and straightsAndFlushesValid. That’s a great idea for performance but because of space constraints, we’re only listing the BestHandNoWild version which is for the case where wild cards are not allowed but straights and flushes are valid (which is probably the typical case for poker). The source code to the remaining cases can be found on-line or on this month’s code disk.

Here is Kevin’s winning solution:

January Solution -Poker-

by Kevin M. Cutts

#include <stdlib.h>
#include <stdio.h>

typedef unsigned char Card;

typedef struct SevenCardHand 
{
 Card cards[7];
} SevenCardHand;

typedef struct FiveCardHand
{
 Card cards[5];
} FiveCardHand;

short ComparePokerHands(
 SevenCardHand *, 
 SevenCardHand *,
 FiveCardHand *,
 FiveCardHand *,
 Boolean,
 Card,
 Boolean,
 void *); 

/* Used to remove the suit information and leave only the count from the card */
unsigned char theValue[] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,
0,1,2,3,4,5,6,7,8,9,10,11,12,
0,1,2,3,4,5,6,7,8,9,10,11,12,
0,1,2,3,4,5,6,7,8,9,10,11,12,
};

/* Used to remove card value and leave the suit indicator */
unsigned char theSuit[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,
};

/* A bit for each card value (aces have two bits) */
unsigned short theValueBit[] = {
0x1000,0x800,0x400,0x200,0x100,0x80,0x40,
 0x20,0x10,0x8,0x4,0x2,0x2001,
0x1000,0x800,0x400,0x200,0x100,0x80,0x40,
 0x20,0x10,0x8,0x4,0x2,0x2001,
0x1000,0x800,0x400,0x200,0x100,0x80,0x40,
 0x20,0x10,0x8,0x4,0x2,0x2001,
0x1000,0x800,0x400,0x200,0x100,0x80,0x40,
 0x20,0x10,0x8,0x4,0x2,0x2001,
};

#define fiveAlike0xa000
#define straightFlush0x9000
#define fourAlike0x8000
#define fullHouse0x7000
#define flush    0x6000
#define straight 0x5000
#define threeAlike 0x4000
#define twoPair  0x3000
#define pair0x2000

#define nonCard 0xff
/* These four functions are custom to handle the four bools wild and flush */
unsigned int BestHandNoWild(SevenCardHand *theHand, 
 FiveCardHand *theBest);
unsigned int BestHand(SevenCardHand *theHand, 
 FiveCardHand *theBest, Card wildCard);
unsigned int BestHandNoFlush(SevenCardHand *theHand, 
 FiveCardHand *theBest, Card wildCard);
unsigned int BestHandNoFlushNoWild(SevenCardHand *theHand, 
 FiveCardHand *theBest);

BestHandNoWild

unsigned int BestHandNoWild(SevenCardHand *theHand, 
 FiveCardHand *theBest)
{
    /* How many of each card value encountered */
 unsigned char handValues[13];
    /* How many of each suit encountered */ 
 unsigned char handSuits[4];
    /* Bit field describing on a suit by suit basis how populated the hand is */ 
 short handRuns[4]; 
 register short i;
 short j;
 Card bestCard, bestPair, goodPair, bestTri, bestQuad;
 Card *cardPtr;
 short runSweep, runResult, runCount;

    /* Zero out all of the counts */
 *(long *)&handValues[0] = 
 *(long *)&handValues[4] = 
 *(long *)&handValues[8] = 
 handValues[12] = 0;
 *(long *)&handSuits[0] = 0;
 *(long *)&handRuns[0] = *(long *)&handRuns[2] = 0;

    /* Now accumulate the values */
 for (i=0, cardPtr=theHand->cards; i<7; i++, cardPtr++)
 {
 handValues[theValue[*cardPtr]]++;
 handSuits[theSuit[*cardPtr]]++;
 handRuns[theSuit[*cardPtr]] |= theValueBit[*cardPtr];
 }
    /* First count the pairs, tris, quads and penta */
 bestCard = bestPair = goodPair = bestTri = bestQuad = nonCard;
 for (i = 12; i >= 0; i--)
 {
 if (!(j = handValues[i])) continue;
 if (j == 4)
 {
 bestQuad = i;
 break;
 }
 if (j == 3 && bestTri == nonCard)
 {
 bestTri = i;
 if (bestPair != nonCard)
 {
 /* Full house */
 break;
 }
 }
 else if (j == 2 && bestPair == nonCard)
 {
 bestPair = i;
 if (bestTri != nonCard)
 {
 /* Full house */
 break;
 }
 }
 else if (j == 2 && goodPair == nonCard)
 {
 goodPair = i;
 }
 else if (bestCard == nonCard)
 {
 bestCard = i;
 }
 }
    /* Now check for a straight flush */
#define CHK_SUIT_NOWILD(suit) \
 if (handSuits[suit] >= 5) \
 { \
 for (runSweep=0x1f;runSweep<0x1fff;runSweep<<= 1) \
 { \
 runResult = handRuns[suit] & runSweep; \
 if (runResult == runSweep) \
 { \
 /* Transfer the five cards */ \
 for (i=0, j=0; j < 5;i++) \
 { \
 if ((theValueBit[theHand->cards[i]] & \
 runSweep && suit == \
 theSuit[theHand->cards[i]])) \
 { \
 theBest->cards[j++] = \
 theHand->cards[i]; \
 } \
 } \
 return straightFlush; \
 } \
 } \
 }
 CHK_SUIT_NOWILD(0);
 CHK_SUIT_NOWILD(1);
 CHK_SUIT_NOWILD(2);
 CHK_SUIT_NOWILD(3);
    /* Next comes four of a kind */
 if (bestQuad != nonCard)
 {
    /* Transfer the five cards */
 runSweep = 1;
 for (i=0, j=0; j < 5;i++)
 {
 if (theValue[theHand->cards[i]] == bestQuad)
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 else if (runSweep)
 {
 theBest->cards[j++] = theHand->cards[i];
 runSweep--;
 }
 }
 return fourAlike | bestQuad;
 }
    /* Next is the full house */
 if (bestTri != nonCard && bestPair != nonCard)
 {
    /* Transfer the five cards */
 for (i=0, j=0; j < 5;i++)
 {
 if (theValue[theHand->cards[i]] == bestTri || 
 theValue[theHand->cards[i]] == bestPair)
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 }
 return fullHouse | (bestTri<<8) | (bestPair);
 }
    /* Now the flush */
#define CHK_FLUSH_NOWILD(suit) \
 if (handSuits[suit] >= 5) \
 { \
    /* Transfer the five cards */ \
 for (i=0, j=0; j < 5;i++) \
 { \
 if (theSuit[theHand->cards[i]] == suit) \
 { \
 theBest->cards[j++] = theHand->cards[i]; \
 } \
 } \
 return flush | bestCard; \
 }
 CHK_FLUSH_NOWILD(0);
 CHK_FLUSH_NOWILD(1);
 CHK_FLUSH_NOWILD(2);
 CHK_FLUSH_NOWILD(3);
    /* Next the straight */
 j = handRuns[0]|handRuns[1]|handRuns[2] | handRuns[3];
 for (runSweep=0x1f; runSweep < 0x1fff; runSweep <<= 1)
 {
 runResult = j & runSweep;
 if (runResult == runSweep)
 {
    /* Transfer the five cards */
 for (i=0, j=0; j < 5;i++)
 {
 if ((theValueBit[theHand->cards[i]] & runSweep))
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 }
 return straight;
 }
 }
    /* and the three of a kind */
 if (bestTri != nonCard)
 {
    /* Transfer the five cards */
 runSweep = 2;
 for (i=0, j=0; j < 5;i++)
 {
 if (theValue[theHand->cards[i]] == bestTri)
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 else if (runSweep)
 {
 theBest->cards[j++] = theHand->cards[i];
 runSweep--;
 }
 }
 return threeAlike | bestTri;
 }
    /* Now two pair */
 if (bestPair != nonCard && goodPair != nonCard)
 {
    /* Transfer the five cards */
 runSweep = 1;
 for (i=0, j=0; j < 5;i++)
 {
 if (theValue[theHand->cards[i]] == bestPair ||
 theValue[theHand->cards[i]] == goodPair)
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 else if (runSweep)
 {
 theBest->cards[j++] = theHand->cards[i];
 runSweep--;
 }
 }
 return twoPair | (bestPair << 8) | goodPair;
 }
    /* And finally a single pair */
 if (bestPair != nonCard)
 {
    /* Transfer the five cards */
 runSweep = 3;
 for (i=0, j=0; j < 5;i++)
 {
 if (theValue[theHand->cards[i]] == bestPair)
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 else if (runSweep)
 {
 theBest->cards[j++] = theHand->cards[i];
 runSweep--;
 }
 }
 return pair | bestPair;
 }
    /* Transfer the five cards */
 runSweep = 4;
 for (i=0, j=0; j < 5;i++)
 {
 if (theValue[theHand->cards[i]] == bestCard)
 {
 theBest->cards[j++] = theHand->cards[i];
 }
 else if (runSweep)
 {
 theBest->cards[j++] = theHand->cards[i];
 runSweep--;
 }
 }
 return bestCard;
}

ComparePokerHands

short ComparePokerHands(
 SevenCardHand *hand1Ptr, 
 SevenCardHand *hand2Ptr,
 FiveCardHand *best1Ptr,
 FiveCardHand *best2Ptr,
 Boolean wildCardAllowed,
 Card wildCard,
 Boolean straightsdAndFlushesValid,
 void *privateDataPtr)
{
 unsigned int hand1Value, hand2Value;
 if (wildCardAllowed && straightsdAndFlushesValid)
 {
 hand1Value = BestHand(hand1Ptr, best1Ptr, wildCard);
 hand2Value = BestHand(hand2Ptr, best2Ptr, wildCard);
 }
 else if (wildCardAllowed)
 {
 hand1Value = BestHandNoFlush(hand1Ptr,best1Ptr,wildCard);
 hand2Value = BestHandNoFlush(hand2Ptr,best2Ptr,wildCard);
 }
 else if (straightsdAndFlushesValid)
 {
 hand1Value = BestHandNoWild(hand1Ptr, best1Ptr);
 hand2Value = BestHandNoWild(hand2Ptr, best2Ptr);
 }
 else
 {
 hand1Value = BestHandNoFlushNoWild(hand1Ptr, best1Ptr);
 hand2Value = BestHandNoFlushNoWild(hand2Ptr, best2Ptr);
 }
 if (hand1Value > hand2Value) return -1;
 if (hand1Value < hand2Value) return 1;
 return 0;
} 

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
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
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.