7

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.

4

2 に答える 2

13

次のようなものを試してください

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

警告 -- 私はそのコードをテストしていませんが、問題の解決に役立つはずです。

于 2009-09-17T12:06:10.443 に答える
3

アルゴリズムをもう一度見直す必要があります。ループを通過するたびに、1 つのアイテムを (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

于 2009-09-17T13:12:59.137 に答える