Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,538 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,520 people online right now. Registration is fast and FREE... Join Now!




How to Compare two 2D arrays efficiently in C

 
Reply to this topicStart new topic

How to Compare two 2D arrays efficiently in C

cyborg36
23 Nov, 2007 - 10:33 AM
Post #1

New D.I.C Head
*

Joined: 23 Nov, 2007
Posts: 1


My Contributions
I am trying to compare two 2D arrays of character type, is there any efficient method to increase the speed of comparing the two arrays in C?

i have done a bit of optimazation but still not getting the desired result.

Any help will be highly apprecaited smile.gif

CODE

for(row=0;row<5;row++)
            {
                if(duplicate == 0)
                {
                    break;
                }
                for(col=0;col<5;col++)
                {
                    if(peg[i].position[row][col] == peg[boardNum].position[row][col])
                    {
                        duplicate = 1;
                    }
                    else
                    {
                        duplicate = 0;
                        break;
                    }
                }
            }

User is offlineProfile CardPM
+Quote Post

NickDMax
RE: How To Compare Two 2D Arrays Efficiently In C
23 Nov, 2007 - 01:05 PM
Post #2

2B||!2B
Group Icon

Joined: 18 Feb, 2007
Posts: 2,868



Thanked: 53 times
Dream Kudos: 550
My Contributions
In general to compare two arrays you really have to go element for element unless there is some property of the data that allows you to logically skip sections. For example if the data is sorted and each element is unique then you can compare the first and last values and if they are the same then the entire array is the same.

There are some commands in C that *can* speed things up for you, for example the memcmp() will speed up the program, but there are some things you should be aware of before you use it.

some compilers think it is nice to "align" your data for you. This is because in some computers memory access works much faster if the data is aligned (set to an "even" address or aligned to a paragraph etc.). So the compiler will pad structures and arrays so that they align. There is no telling what the padded values might be, and they may cause memcmp() to fail. So, how do you combat this? One way is to compare only one row at a time.
User is online!Profile CardPM
+Quote Post

barnwillyb
RE: How To Compare Two 2D Arrays Efficiently In C
23 Nov, 2007 - 02:50 PM
Post #3

D.I.C Head
**

Joined: 22 May, 2007
Posts: 55


My Contributions
QUOTE(cyborg36 @ 23 Nov, 2007 - 11:33 AM) *

I am trying to compare two 2D arrays of character type, is there any efficient method to increase the speed of comparing the two arrays in C?

i have done a bit of optimazation but still not getting the desired result.

Any help will be highly apprecaited smile.gif

CODE

for(row=0;row<5;row++)
            {
                if(duplicate == 0)
                {
                    break;
                }
                for(col=0;col<5;col++)
                {
                    if(peg[i].position[row][col] == peg[boardNum].position[row][col])
                    {
                        duplicate = 1;
                    }
                    else
                    {
                        duplicate = 0;
                        break;
                    }
                }
            }



Here is a program that compares drawn lotto numbers with winning lotto numbers:

CODE
/*__________________________________________________________*/
/*                                                                                                                    */
/*                                                 includes                                                    */
/*__________________________________________________________*/

#import <Cocoa/Cocoa.h>

/*__________________________________________________________*/
/*                                                                                                                    */
/*                        definitions                                                */
/*__________________________________________________________*/

#define    kLottoSize        6

#define    kNoMatch            "\n\t\t\t\t\tSORRY MAYBE NEXT TIME!"

#define    kOneMatch            "\n\t\t\t\t\tSorry, there is only one match!"

#define    kTwoMatches        "\n\t\t\t\t\tSorry, there is only two matches!"

#define    kThreeMatches    "\n\t\t\t\t\tThis is a winner with three matches!"

#define    kFourMatches    "\n\t\t\t\t\tThis is a winner with four matches!"

#define    kFiveMatches    "\n\t\t\t\t\tThis is a winner with five matches!"

#define    kSixMatches        "\n\t\t\t\t\tThis is a winner with six matches!"

/*__________________________________________________________*/
/*                                                                                                                    */
/*                          globals                                                    */
/*__________________________________________________________*/

int drwnArray[ kLottoSize ];
int winArray[ kLottoSize ];

/*__________________________________________________________*/
/*                                                                                                                    */
/*                        prototypes                                                */
/*__________________________________________________________*/

void NumbersToCheck( void );
void DrawnNumbers( void );
void WinningNumbers();
void DuplicateDrwnNums( void );
void DuplicateWinNums( void );
void DupDrwnAlert( void );
void DupWinAlert( void );
void FindMatch( void );

/*__________________________________________________________*/
/*                                                                                                                    */
/*                                             main listing                                                */
/*__________________________________________________________*/

int main(int argc, char *argv[]) {
    short    moreNums;
    char    doneEnteringNums, *result;

    doneEnteringNums = false;
    moreNums = 0;

    printf( "\n\t  ___________________________________________________________________\n\n" );
    
    WinningNumbers();

    while (! doneEnteringNums){
        NumbersToCheck();
        FindMatch();
        
        if ((result == NULL) || (result[0] == '\0'))
            doneEnteringNums = true;    
        else
            moreNums++;
    }

    return 0;
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                                            numbers to check                                        */
/*__________________________________________________________*/

void NumbersToCheck( void )
{
    int    i;

    DrawnNumbers();

    printf( "\n\t\t\t\tThe drawn numbers in order are: " );
    for (i = 0; i < kLottoSize; ++i)
        printf( "%2d ", drwnArray[i] );

    printf( "\n\t\t\tThe winning numbers in order are: " );
    for (i = 0; i < kLottoSize; ++i)
        printf( "%2d ", winArray[i] );
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                                        find lotto matches                                        */
/*__________________________________________________________*/

void FindMatch( void )
{
    int        nAddr, elAddr, match;

    printf( "\n" );

    match = 0;
    for (elAddr = 0; elAddr < kLottoSize; ++elAddr)
    {
        printf( "\n\t\t\t\t  Comparing %d with the winning numbers:\n"
                        "\t\t\t\t  ——————————————————————————————————————", drwnArray[ elAddr ] );                    // 35 11 49 7 28 2
        for (nAddr = 0; nAddr < kLottoSize; ++nAddr)
        {
            printf( "\n\t\t\t\t  " );
            printf( "drwnArray[%d] = %2d ===> winNums[%d]"
                                " = %2d", elAddr, drwnArray[ elAddr ], nAddr, winArray[ nAddr ] );
            if (drwnArray[ elAddr ] == winArray[ nAddr ])
            {
                    ++match;
                    printf( " <——— match #%d", match );
                }
        }
        printf( "\n\t\t\t\t  ——————————————————————————————————————\n"
                        "\t\t\t\t\t\t\t   MATCH ——> #%d\n", match );
    }
    if (match == 0)
        printf( kNoMatch );

    else if (match == 1)
        printf( kOneMatch );

    else if (match == 2)
        printf( kTwoMatches );

    else if (match == 3)
        printf( kThreeMatches );

    else if (match == 4)
        printf( kFourMatches );

    else if (match == 5)
        printf( kFiveMatches );

    else if (match == 6)
        printf( kSixMatches );                                                            

    printf( "\n\n\t  ___________________________________________________________________\n" );
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                                    winning lotto numbers                                        */
/*__________________________________________________________*/

void WinningNumbers( void )
{
    int i, hCnt, tmp;

    printf( "\t\t\tEnter six winning lotto numbers: " );

    for (i = 0; i < kLottoSize; ++i)
    {
        scanf( "%d", &winArray[i] );
    }

    for (i = 0; i < kLottoSize - 1; ++i)        
        for (hCnt = kLottoSize - 1; hCnt > i; --hCnt)
            if (winArray[hCnt-1] > winArray[hCnt])
            {
                tmp = winArray[hCnt-1];
                winArray[hCnt-1] = winArray[hCnt];
                winArray[hCnt] = tmp;
            }
            DuplicateWinNums();
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                 check duplicate winning numbers                                    */
/*__________________________________________________________*/

void DuplicateWinNums( void )
{
    int i, winCnt, dup;

    for (i = 0; i < kLottoSize; i++)
    {
        winArray[i];
        dup = 0;
        for (winCnt = 0; winCnt < i; winCnt++)
        {
            if (winArray[i] == winArray[ winCnt ])    /*    if match found set flag.  */
                dup++;
        }
        if (dup > 0)
            DupWinAlert();
    }
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                                        drawn lotto numbers                                        */
/*__________________________________________________________*/

void DrawnNumbers( void )
{
    int i, hCnt, tmp;

    printf( "\t\t\t\tEnter six drawn lotto numbers: " );

    for (i = 0; i < kLottoSize; ++i)
    {
        scanf( "%d", &drwnArray[i] );
    }
    for (i = 0; i < kLottoSize - 1; ++i)
        for (hCnt = kLottoSize - 1; hCnt > i; --hCnt)
            if (drwnArray[hCnt-1] > drwnArray[hCnt])
            {
                tmp = drwnArray[hCnt-1];
                drwnArray[hCnt-1] = drwnArray[hCnt];
                drwnArray[hCnt] = tmp;
            }
            DuplicateDrwnNums();
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                         check duplicate drawn numbers                                */
/*__________________________________________________________*/

void DuplicateDrwnNums( void )
{
    int i, drwnCnt, dup;

    for (i = 0; i < kLottoSize; i++)
    {
        drwnArray[i];
        dup = 0;
        for (drwnCnt = 0; drwnCnt < i; drwnCnt++)
        {
            if (drwnArray[i] == drwnArray[ drwnCnt ])    /*    if match found - set flag.  */
                dup++;
        }
        if (dup > 0)
            DupDrwnAlert();
    }
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                                duplicate winning warning                                    */
/*__________________________________________________________*/

void DupWinAlert( void )
{
    printf("\n\t\t\t\tLOTTO NUMBERS CANNOT BE DUPLICATED!\n\n" );

    WinningNumbers();
}

/*__________________________________________________________*/
/*                                                                                                                    */
/*                          duplicate drawn warning                                    */
/*__________________________________________________________*/

void DupDrwnAlert( void )
{
    printf("\n\t\t\t\tLOTTO NUMBERS CANNOT BE DUPLICATED!\n\n" );

    DrawnNumbers();
}


Hope that puts you on the right track!
barnwillyb
User is offlineProfile CardPM
+Quote Post

baavgai
RE: How To Compare Two 2D Arrays Efficiently In C
23 Nov, 2007 - 04:29 PM
Post #4

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,277



Thanked: 135 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua, Cheese

My Contributions
The code you have could be made a little shorter, You don't need the duplicate = 1;, for example:

So, functions are your friends:
CODE
int isMatch(PegType *peg1, PegType *peg2) {
   for(int row=0;row<5;row++) {
      for(int col=0;col<5;col++) {
         if(peg1->position[row][col] != peg2->position[row][col]) {
            return 0;
         }
      }
   }
   return 1;
}

if (isMatch(&peg[i], &peg[boardNum])) { ...


That saves a little checking, and a variable assignment, so should be marginally faster. However, the logic is the same, loop and check, that's really all you can do.

Hope this helps.

This post has been edited by baavgai: 23 Nov, 2007 - 04:29 PM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/7/09 09:17PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month