我以为我有,

void shiftArray(NSMutableArray *mutableArray, NSUInteger shift)
{
    for (NSUInteger i = 0; i < [mutableArray count]; i++) {
        NSUInteger newIndex = (i + shift) % [mutableArray count];
        [mutableArray exchangeObjectAtIndex:i withObjectAtIndex:newIndex];
    }
}
当我换一个时,

将0,1,2,3,4变成0,2,3,4,1。

预期结果为4,0,1,2,3

我觉得我错过了一些明显的东西......

更新:感谢Matthieu,这就是我现在的功能。

void shiftArrayRight(NSMutableArray *mutableArray, NSUInteger shift) {
    for (NSUInteger i = shift; i > 0; i--) {
        NSObject *obj = [mutableArray lastObject];
        [mutableArray insertObject:obj atIndex:0];
        [mutableArray removeLastObject];
    }
}

我不知道你可以制作一个通用的NSObject并在其中加入一些子类。它只是指针所以我猜它没关系,对吧?

很难打破将这些物体视为 bag 的东西而不是指针的习惯。

有帮助吗?

解决方案

尝试类似

的内容
for (NSUInteger i = shift; i > 0; i--) {
   NSObject* obj = [mutableArray lastObject];
   [mutableArray insertObject:obj atIndex:0];
   [mutableArray removeLastObject];
}

CAVEAT - 我没有测试过该代码,但这可以帮助您解决问题。

其他提示

您需要再次查看您的算法。每次循环时,您将交换一个项目(在shift = 1的情况下)下一个项目。

0,1,2,3,4,点击 的 1 ,<强> 0 下,2,3,4,点击 1,<强> 2 ,<强> 0 下,3,4,点击 1,2,<强> 3 ,<强> 0 下,4,点击 1,2,3,的 4 ,<强> 0 结果 的 0 下,2,3,4,的 1 结果

您可以执行您想要执行的操作,但您需要考虑如何订购步骤及其依赖项以获得正确的结果。在这个简单的案例中,你可以从最后开始向后工作。

0,1,2,3,4,点击 的 4 下,1,2,3,的 0 结果 4,1,2,的 0 ,<强> 3 结果 4,1,的 0 ,<强> 2 下,3,点击 4,<强> 0 ,<强> 1 下,2,3-结果

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top