iphone随机数问题

时间:2009-07-27 17:09:57

标签: iphone

我在DB中有52条记录,获取这些记录并存储在数组中。现在我想将它们分配到四个数组中,每个数组只有7个记录,因此只有28个记录将在4个数组中,剩下的将在新的临时数组中。实际上这是一个基于卡片的游戏,有四个玩家,卡片会像这样分发:从第一个玩家第一张牌开始,第二个玩家第二张,第三个玩家第三张,第四个玩家第四张。当每位玩家有7张牌时,此过程将重复。

所以我如何分配它们,以便相同的卡可能性最小化。我应该使用随机数或任何新的...请建议

谢谢,

Aaryan

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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伪代码;)