交换NSArray的后半部分与上半部分

时间:2014-12-07 12:35:52

标签: ios objective-c algorithm sorting nsmutablearray

我有一个NSMutableArray按特定顺序包含十个自定义对象。

我需要重新排列对象,以便数组的后半部分与前半部分交错:

之前:1,2,3,4,5,6,7,8,9,10 之后:1,6,2,7,3,8,4,9,5,10

我该如何做到这一点?

3 个答案:

答案 0 :(得分:1)

  • (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2

  • (无效)sortUsingComparator:(NSComparator)CMPTR

答案 1 :(得分:1)

您正在寻找的是shuffle(想想洗牌一副牌 - 相同的数据,不同的顺序)。以下方法可用于swap two objects within a mutable array.

- (void)exchangeObjectAtIndex:(NSUInteger)idx1
        withObjectAtIndex:(NSUInteger)idx2

在修改数组时,不能枚举数组,并且我也不会循环遍历数组的元素。相反,使用索引创建一个for循环并使用arc4random生成第二个交换索引。

for (NSUInteger n = 0; n < array.count; n++) {
    NSUInteger m = arc4random_uniform(array.count);
    [array exchangeObjectAtIndex:n withObjectAtIndex:m];
}

可以添加更复杂的内容,例如检查是否n == m或否定某种偏见,但这应该会让你成为一个&#34;大多数&#34;原始数组的随机抽样。


[夫特]

Swift exchange方法在可变数组中交换两个项目。     func exchangeObjectAtIndex(_ idx1:Int,          withObjectAtIndex idx2:Int)

用户Nate Cook提供了几个好shuffling methods for Swift here.我在这里复制他的变异Array方法,因为它最接近上述Objective-C方法。

extension Array {
    mutating func shuffle() {
        for i in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            exchangeObjectAtIndex(i, withObjectAtIndex: j)
        }
    }
}
var numbers = [1, 2, 3, 4, 5, 6, 7, 8]
numbers.shuffle() 

答案 2 :(得分:0)

为什么不创建第二个NSArray,在其中按您想要的顺序放置值?之后,如果您想使用第一个数组,则从中删除所有项目

[firstArray removeAllObjects];

然后将项目放回第二个数组:

for (int i = 0; i < [secondArray count]; i++)
{
[firstArray addObject: [secondArray objectAtIndex:i]];
}
相关问题