我可以在不创建临时数组的情况下移动 NSMutableArray 中的对象吗?
我以为我已经有了它,
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 并在其中放入一些子类。这只是指针,所以我想没关系,对吧?
很难打破将这些对象视为东西的袋子而不是指向袋子的指针的习惯。
I thought I had it with,
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];
}
}
which turns 0,1,2,3,4 into 0,2,3,4,1 when I shift by one.
The expected result is 4,0,1,2,3
I feel like I'm missing something obvious...
Update: Thanks Matthieu, this is what my function looks like now.
void shiftArrayRight(NSMutableArray *mutableArray, NSUInteger shift) {
for (NSUInteger i = shift; i > 0; i--) {
NSObject *obj = [mutableArray lastObject];
[mutableArray insertObject:obj atIndex:0];
[mutableArray removeLastObject];
}
}
I didn't know you could make a generic NSObject and put some subclass in it. It's all just pointers so I guess it's OK, right?
It's hard to break the habit of thinking of these objects as bags of stuff rather than pointers to the bag.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试类似
CAVEAT 的方法——我还没有测试过该代码,但这应该可以帮助您解决问题。
Try something like
CAVEAT -- I haven't tested that code, but that should help you solve the problem.
您需要再次查看您的算法。每次循环时,您都会将一项与下一项交换(在 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
You need to look again at your algorithm. Each time through the loop, you exchange one item with (in the case of shift=1) the next one.
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
You can do the operation you want to do, but you need to think about how to order the steps and their dependencies to get the right result. In the trivial case, you can just work backward from the end.
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