2014-03-06 113 views
0

我有一個NSArray與卡對象具有不同的值,讓我們說1,2,3,5,8,10。我想確定一張卡是否可播放,我用播放器他卡對象的屬性,這顯然也具有價值屬性。規則是,當一張卡片可以播放時(這個例子中只有卡片1可以播放),只有不同值的卡片也可以播放。所以在上面的例子中,卡號2也是可播放的,其餘的不是。要清楚,排序可能不同,並不總是上升或下降。通過NSArray迭代並計算差異

我想要的是遍歷playerCards數組,並將數組中的所有其他卡片進行比較,當差值爲1時,將卡片的可玩屬性設置爲IsPlayable,然後再次循環,直到確定所有可玩卡片。

First loop attempt (card 1 is playable): 
2-1 = 1 card value 2 is playable 
3-1 = 2 card value 3 is not playable 
5-1 = 4 card value 5 is not playable 
8-1 = 7 card value 8 is not playable 
10-1 = 9 card value 10 is not playable 

Second loop attempt (card 2 is now also playable): 
3-2 = 1 card value 3 is playable 
5-2 = 3 card value 5 is not playable 
8-2 = 6 card value 8 is not playable 
10-2 = 8 card value 10 is not playable 

Third loop attempt (card 3 is now also playable): 
5-3 = 2 card value 5 is not playable 
8-3 = 5 card value 8 is not playable 
10-3 = 7 card value 10 is not playable 

Stop loop. 

我不知道該怎麼去。這是我到目前爲止,但我迷路了;

for(int x = 0; x < [playerCards count]; x++) 
{  
Card *playerCard = [playerCards objectAtIndex:x]; 
if(playerCard.playable == IsPlayable){ 
something like playerCard.value-otherplayerCard.value ???} 

你們能幫忙嗎?

謝謝!

+0

如果您只是發佈作業的原文,會更容易理解。 –

回答

0

你可以把你的for循環在while循環,其中如果做出更改的while迴路檢查和for循環做出改變(或不如果樣樣齊全)。

我要去假設Card類有一個名爲NSNumbercard

BOOL changed = YES; 
NSMutableArray *playableCards = [NSMutableArray array]; 

while (changed) { 

    changed = NO; 

    for (Card *playerCard in playerCards) { 
     NSNumber *card = playerCard.card; 

     if (playerCard.playable == IsPlayable) { 
      if (![playableCards containsObject:card]) { 
       NSLog(@"Card %@ is already playable", playerCard.card); 
       [playableCards addObject:card]; 
       changed = YES; 
      } 
     } else { 
      NSNumber *cardUp = @(card.integerValue + 1); 
      NSNumber *cardDown = @(card.integerValue - 1); 

      if ([playableCards containsObject:cardUp] || [playableCards containsObject:cardDown]) { 
       NSLog(@"Card %@ is being made playable", playerCard.card); 
       changed = YES; 
       playerCard.playable = IsPlayable; 
       [playableCards addObject:card]; 
      } 
     } 
    } 
} 
+0

謝謝Wain,它幫了我很多!現在我唯一的問題是代碼不斷地繼續下去。我如何確定是否所有可能的計算都已完成,然後退出循環? – Niels

+0

已編輯。需要改變初始條件... – Wain

+0

感謝您的快速答覆,但它仍然循環到無限... – Niels

0

這裏有一個通用的編程模式,將在其他地方有用。模式是,你從一些有限的信息開始,並可能增加更多的信息,從而導致更多的信息;在這種情況下,「可播放」卡片最初是標記爲可播放的卡片,然後附近的可播放卡片變爲可播放的,等等。模式是

"start with initial data" 
BOOL changed = YES; 

while (changed) 
{ 
    changed = NO; 
    "try to find any new information" 
    if ("any new information was found") 
     changed = YES; 
}