2009-07-27 43 views
0

我在数据库中有52条记录,获取这些数据并存储在数组中。现在我想将它们分配到四个数组中,每个数组只有7个记录,所以只有28个记录将在4个数组中,其余的将存放在新的temp数组中。实际上这是一款基于卡牌的游戏,拥有四名玩家,卡牌的分布情况如下:从第一个玩家第一个玩家卡片开始,第二个玩家第二个卡片,第三个玩家第三个玩家,第四个玩家第四个玩家开始。这个过程将会重复,每个玩家有7张牌。iphone随机数发行

所以我如何分配他们,以便相同的卡片可能性变得最小化。我应该怎么处理由随机数或任何新......请建议

感谢,

Aaryan

回答

1

下面是NSMutableArray的一个类别,用于将数组随机移动。它在小阵列上做的不错,但请注意,使用的随机数函数mrand48()没有足够的随机性来产生一副牌的所有可能的混洗,所以在产生的混洗中存在一些偏差。如果你的游戏纯粹是为了娱乐,这可能就足够了。如果没有,您可以用更好的发生器替换mrand48()

不要忘记在srand48()启动时播种随机数发生器。

// --- NSMutableArray+Random.h --- 
#import <Foundation/Foundation.h> 

@interface NSMutableArray (Random) 
    /// Shuffle a mutable array in place. Uses a Fisher-Yates shuffle as described 
    /// in http://en.wikipedia.org/wiki/Fisher-Yates_shuffle . 
    - (void)shuffle; 
@end 

// --- NSMutableArray+Random.m 
#import "NSMutableArray+Random.h" 

/// Return a pseudo-random unsigned integer in the range 
/// [0, exclusiveUpperBound) using the mrand48() function. 
/// Seed the random number state by calling srand48(). 
/// See http://developer.apple.com/iphone/library/documentation/System/Conceptual/ManPages_iPhoneOS/man3/rand48.3.html 
static NSUInteger randomUIntegerFromZeroUpTo(NSUInteger exclusiveUpperBound) { 
    NSUInteger const maxUInteger = 0xffffffff; 
    NSUInteger largestMultipleOfMaxUInteger 
     = maxUInteger - (maxUInteger % exclusiveUpperBound); 
    // discard random integers outside the range [0, largestMultipleOfMaxUnsignedInteger) 
    // to eliminate modulo bias 
    NSUInteger randomUInteger; 
    do { 
    randomUInteger = (NSUInteger) mrand48(); 
    } while (randomUInteger >= largestMultipleOfMaxUInteger); 
    return randomUInteger % exclusiveUpperBound; 
} 

@implementation NSMutableArray (Random) 
- (void)shuffle { 
    for (NSUInteger unshuffled = self.count; unshuffled > 1; --unshuffled) { 
    NSUInteger index1 = unshuffled - 1; 
    NSUInteger index2 = randomUIntegerFromZeroUpTo(unshuffled); 
    [self exchangeObjectAtIndex:index1 withObjectAtIndex:index2]; 
    } 
} 
@end 
0

你应该看看this answer about Shuffle Bag

当你发布你的卡,你让你的52卡的列表,做这样的事情:

listOfCards = { /* init, order not important */ } 
cardsToDistribute = [] 

28.times do 
    nextCard = listOfCards[random(0, listOfCards.size)] 

    listOfCards.remove(nextCard) //side effect: decrement listOfCards.size by 1 

    cardsToDistribute << nextCard 
end 

7.times do 
    player1.cards << cardsToDistribute.removeFirst //side effect: decrement cardsToDistribute.size by 1 
    player2.cards << cardsToDistribute.removeFirst 
    player3.cards << cardsToDistribute.removeFirst 
    player4.cards << cardsToDistribute.removeFirst 
end 

(对不起,我不知道Objective-C的非常好,所以这是Rubyist伪代码;)