baskon1
baskon1

Reputation: 330

Comparing all structure items with specific rules

I have a structure with 4 items inside.

typedef struct
    {
    char colour;
    char shape;
    char nr;
    char p;
    }CARDS;

This structure has many items inside and I want to compare them 3 by 3.. so compare for example cards[1], cards[2],cards[3]. If 3/4 of the elements between the 3 cards are equal then we have a SET so set=1. If no elements are equal we again have set=1.

For sure I could just write many If

If (cards[1].colour=cards[2].colour=cards[3].colour)
    counter = counter +1;
If (cards[1].shape=cards[2].shape=cards[3].shape)
    counter=counter+1;
If (cards[1].nr=cards[2].nr=cards[3].nr)
    counter=counter+1;
If (cards[1].p=cards[2].p=cards[3].p)
    counter=counter+1;

and then make an if statement for counter

 If (counter==3||counter==0)
     set=1;

Is there any other more elegant way to do it?

Upvotes: 0

Views: 81

Answers (3)

bunty
bunty

Reputation: 629

There is a serious bug in the condition, there should be a greater than: If 3/4 of the elements between the 3 cards

if (counter >= 3 || counter==0)
     set=1;

Upvotes: 0

Ryan Haining
Ryan Haining

Reputation: 36882

First off you are using = when you should be using ==, compile with warnings to see this. You are also attempting to compare three things at once. You can't do if (a == b == c) but must instead do if (a == b && a == c) or similar.

A true == result is equal to 1 and you can use that here by just adding it up:

int count = 
    (cards[1].colour == cards[2].colour && cards[1].colour == cards[3].colour)
    + (cards[1].shape == cards[2].shape && cards[1].shape == cards[3].shape)
    + (cards[1].nr == cards[2].nr && cards[1].nr == cards[3].nr)
    + (cards[1].p == cards[2].p && cards[1].p == cards[3].p);

int set = count == 3 || count == 0;

Upvotes: 3

Paul R
Paul R

Reputation: 213130

You could make your data structure more amenable to this kind of comparison, e.g.

typedef enum {
    COLOUR,
    SHAPE,
    NR,
    P,
    NUM_ATTRS
} ATTRS;

typedef struct {
    char attrs[NUM_ATTRS];
} CARD;

This enables you to use simple loops to test multiple attributes of multiple cards, rather than hard-coded explicit logic.

Upvotes: 0

Related Questions