Given 4 objects, how to figure out whether exactly 2 have a certain property
Posted
by Cocorico
on Stack Overflow
See other posts from Stack Overflow
or by Cocorico
Published on 2010-03-31T16:10:22Z
Indexed on
2010/03/31
16:13 UTC
Read the original article
Hit count: 319
objective-c
|algorithm
Hi guys! I have another question on how to make most elegant solution to this problem, since I cannot afford to go to computer school right so my actual "pure programming" CS knowledge is not perfect or great. This is basically an algorhythm problem (someone please correct me if I am using that wrong, since I don't want to keep saying them and embarass myself)
I have 4 objects. Each of them has an species property that can either be a dog, cat, pig or monkey. So a sample situation could be:
object1.species=pig object2.species=cat object3.species=pig object4.species=dog
Now, if I want to figure out if all 4 are the same species, I know I could just say:
if ( (object1.species==object2.species)
&& (object2.species==object3.species)
&& (object3.species==object4.species)
) {
// They are all the same animal (don't care WHICH animal they are)
}
But that isn't so elegant right? And if I suddenly want to know if EXACTLY 3 or 2 of them are the same species (don't care WHICH species it is though), suddenly I'm in spaghetti code.
I am using Objective C although I don't know if that matters really, since the most elegant solution to this is I assume the same in all languages conceptually? Anyone got good idea?
Thanks!!
© Stack Overflow or respective owner