随机呈现一对用户,而不再显示相同的对

时间:2013-08-23 03:19:16

标签: ios combinations

我正在尝试弄清楚如何将一组用户中的一对用户呈现给应用的current_user,而不是让current_user再次看到同一对用户。在数学上,我理解这是n choose 2,其中n是用户数组的大小。但是,我不确定如何设置数据结构,以便随机,将所有组合对应呈现给current_user。谢谢!

1 个答案:

答案 0 :(得分:1)

我会创建一个由两个用户的id组成的类。

@interface userPair: NSObject

 @property (nonatomic, assign) NSInteger user1id;
 @property (nonatomic, assign) NSInteger user2id;

@end

我只想创建所有可能对的NSMutableArray然后运行这个非常棒的shuffle方法:(取自this answer

- (void)shuffle
{
    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n = (arc4random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}