通过NSArray迭代并计算差异

时间:2014-03-06 20:02:24

标签: ios loops

我有一个带有不同值的卡片对象的NSArray,比方说1,2,3,5,8,10。我想确定一张卡片是否可以播放,我是用卡片对象的可播放属性做的,这显然也有价值属性。规则是当卡可播放时(对于该示例,只有卡1可播放),具有仅差1的值的卡也是可播放的。所以在上面的例子中,第二张牌也可以玩,剩下的不是。需要明确的是,排序可能有所不同,并不总是上升或下降。

我想要的是遍历playerCards阵列并将1张牌与阵列中的所有其他牌进行比较,当差值为1时,将牌的可玩属性设置为IsPlayable,然后再次循环直到确定所有可玩牌。 / p>

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 ???}
你能帮忙吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以将for循环放在while循环中,其中while循环检查是否进行了更改并且for循环进行了更改(如果一切都很完整。)

我将假设Card类的NSNumber名为card

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];
            }
        }
    }
}

答案 1 :(得分: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;
}