2010-03-31 24 views
2

我有另一個問題如何使這個問題最優雅的解決方案,因爲我不能去計算機學校的權利,所以我的實際「純粹編程」 CS的知識並不完美或很棒。這基本上是一個算法問題(有人請糾正我,如果我使用的是錯誤的,因爲我不想說出他們並使自己不自在)鑑於4個對象,如何確定究竟是否有2個具有某種屬性

我有4個對象。他們每個人都有一種物種財產,可以是狗,貓,豬或猴子。因此,一個樣本的情況可能是:

object1.species =豬 object2.species =貓 object3.species =豬 object4.species =狗

現在,如果我想弄清楚,如果所有4相同的物種,我知道我只能說:

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) 
} 

但是,這不是很優雅的權利?如果我突然想知道它們中的3個或2個是否屬於相同的物種(不管它是哪種物種),突然間我都在用意大利細麪條代碼。

我正在使用Objective C,但我不知道這是否真的很重要,因爲最優雅的解決方案是,我假設所有語言在概念上都是一樣的?任何人有好主意?

謝謝!

回答

1

這正是套和計數套的目的。

BOOL allSameSpecies(NSArray *animals) { 
    NSSet *speciesSet = [NSSet setWithArray:[animals valueForKey:@"species"]]; 
    return [[speciesSet] count] == 1; 
} 

BOOL sameSpeciesNumber(NSArray *animals, NSUInteger targetCount) { 
    NSCountedSet *speciesCounts = [NSCountedSet setWithArray:[animals valueForKey:@"species"]]; 
    for (id species in speciesCounts) { 
     if ([speciesCounts countForObject:species] == targetCount) 
      return YES; 
    } 
    return NO. 
} 
4

您可以使用散列表(或Objective-C中的字典)和物種上的鍵,每次遞增計數。

爲了清晰(僞代碼):

// N is 4 for your particular case 
for (int i = 0; i < N; i++) 
    hashtable[ object[i].species ]++; 

hashtable[ Species.PIG ]; // number of pigs (constant) 

,或者如果你想手動展開它:

hashtable[ object1.species ]++; 
hashtable[ object2.species ]++; 
hashtable[ object3.species ]++; 
hashtable[ object4.species ]++; 

現在你可以通過種檢查,看看計數:

for each key in hashtable 
    if (hashtable[ key ] == 3) // species "key" has 3 items 
     /* Code */ 

當然,如果物種只是一個簡單的枚舉/整數,「hashtable」可以只是一個簡單的數組。無論哪種情況,以上都應該是相同的理論。

+0

+1,對於像這樣的小案例,即使只是一個普通的C數組就足夠了。 – 2010-03-31 16:31:05

+0

我同意,雖然你不得不做一個映射表(除非物種是一個簡單的enum/int),無論如何可能會超過一半。 – Larry 2010-03-31 16:50:46

+0

好的,是的,所以如果我使用4個int值而不是動物名稱,那麼 object1.species = 1; 然後我可以只使用C數組和做這樣的事情: \t \t INT speciesArray [4] = {object1.species,object2.species,object3.species,object4.species}; 然後只需使用一些命令,如 [有多少物種的數組元素是int 0]; 對不對?所以我只需要弄清楚用什麼正確的函數來計算物種陣列中有多少個0? – Cocorico 2010-03-31 17:48:31

1

您可以計算所有可能的比較匹配的比較次數。如果只有1個比較結果爲真,那麼恰好2個項目是相同的,如果3個比較匹配,則恰好3個項目是相同的。這個例子是在C中,你必須自己將它轉換爲Objective-C。

int count = 0; 
count += object1.species == object2.species; 
count += object1.species == object3.species; 
count += object1.species == object4.species; 
count += object2.species == object2.species; 
count += object2.species == object3.species; 
count += object3.species == object4.species; 
// count 0 - all different 
// count 1 - exactly 2 are the same 
// count 2 - two pairs of 2 
// count 3 - exactly 3 are the same 
// count 6 - all are the same 

計數也可以被實現爲一個循環:

for (int i = 0; i < 4; i++) 
    for (int j = i + 1; j < 4; j++) 
     count += objects[i].species == objects[j].species; 

這種方法僅適用如果對象的量爲5或更小。由於這一點以及比較的數量按比例縮放的事實,如果對象數量較大,最好使用散列表。

相關問題