私は配列を持っています
@["A","B","C","D","E","F","G"]
そして、次のように十字に並べ替えたい
@["A","G","B","F","C","E","D"]
最後のアイテムが2回ごとに前に滑り落ちるようにします。
私は配列を持っています
@["A","B","C","D","E","F","G"]
そして、次のように十字に並べ替えたい
@["A","G","B","F","C","E","D"]
最後のアイテムが2回ごとに前に滑り落ちるようにします。
何も試していないことがわかりました。アルゴリズムが見つからない、または頭の中に思い浮かばないことが原因である場合は、次のコードが役立つ可能性があります。
@autoreleasepool
{
BOOL tail= NO; // To know if you should remove from array's tail or head.
NSMutableArray* array=[NSMutableArray arrayWithArray: @[@"A",@"B",@"C",@"D",@"E",@"F",@"G"] ]; // The unsorted array.
// This will contain sorted objects:
NSMutableArray* sorted=[[NSMutableArray alloc]initWithCapacity: array.count];
// The algorithm will end when array will be empty:
while(array.count)
{
NSUInteger index= tail? array.count-1:0; // I decide the index of the object
// to remove.
// The removed object will be added to the sorted array, so that it will
// contain the object on head, then on tail, then again on head, and so on...
id object= array[index];
[sorted addObject: object];
[array removeObjectAtIndex: index];
tail= !tail;
}
NSLog(@"%@",sorted);
}
これは次のように実行できます。
配列を半分に分割します。
両方並べます。
両方を再度マージして、結果を形成します。ここでは、代替手段を反復する必要があります。つまり、step+=2
編集:実行中のコードは次のとおりです
NSArray *array=@[@"A",@"B",@"C",@"D",@"E",@"F",@"G"];
NSArray *halfLeft=[array subarrayWithRange:NSMakeRange(0, array.count/2+1)];
NSMutableArray *halfRight=[NSMutableArray arrayWithArray:array];
[halfRight removeObjectsInArray:halfLeft];
NSMutableArray *finalAray=[[NSMutableArray alloc]initWithArray:halfLeft];
for (NSInteger i=0, index=1; i<halfRight.count; i++, index+=2) {
[finalAray insertObject:halfRight[halfRight.count-1-i] atIndex:index];
}
NSLog(@"%@",finalAray);
単純なループを使用して、オブジェクトを出力配列に追加することができます。
NSArray *input = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H"];
NSMutableArray *output = [[NSMutableArray alloc] init];
// Quickly add all except possibly the middle one, makes the loop simple
for(int i=0; i<input.count/2; i++)
{
[output addObject:input[i]];
[output addObject:input[input.count-i-1]];
}
// If there is an odd number of items, just add the last one separately
if(input.count%2)
[output addObject:input[input.count/2]];