我有另一個問題如何使這個問題最優雅的解決方案,因爲我不能去計算機學校的權利,所以我的實際「純粹編程」 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,對於像這樣的小案例,即使只是一個普通的C數組就足夠了。 – 2010-03-31 16:31:05
我同意,雖然你不得不做一個映射表(除非物種是一個簡單的enum/int),無論如何可能會超過一半。 – Larry 2010-03-31 16:50:46
好的,是的,所以如果我使用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