美文网首页
数组乱序处理

数组乱序处理

作者: pengrain | 来源:发表于2016-04-12 09:15 被阅读374次
//将一个数组元素顺序打乱
+ (NSMutableArray *)gibberishArray:(NSArray *)array{
    NSMutableArray *arr = [NSMutableArray  arrayWithCapacity:array.count];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:array];
    int count = (int)array.count;
    int randCount = 0;//索引
    int nowCount = 0;//当前数组的元素个数

    for (;count != 0; ) {
        nowCount = (int)tempArr.count;//当前数组的元素个数
        count = nowCount;
        if (nowCount != 0) {
            randCount = (arc4random() % nowCount);
            [arr addObject:tempArr[randCount]];
            tempArr[randCount] = tempArr.lastObject;
            [tempArr removeLastObject];
        }
    }
    return arr;
}

相关文章

网友评论

      本文标题:数组乱序处理

      本文链接:https://www.haomeiwen.com/subject/mroilttx.html