Say I have two arrays, one representing a desired order for the other. I'd like to be able to apply the order to the array.
My reasoning is this. My app contains a playlist that can be shuffled and I want to be able to store the shuffled indexes in case a user continues a given playlist later. So, the two main requirements are that I need to be able to extract the indexes of the original playlist in the shuffled list, and later to be able to reapply those indexes to the the original playlist to regenerate the exact same shuffled list (my shuffle method is random, it will be different every time).
Here is my naive approach. My main questions are, what is the most efficient way to do this, and what is the best way to store the "order" array - clearly using an array of NSNumbers is not efficient, but I'm still an amateur and don't know how to do it better.
NSMutableArray *anArray = @[@"this",@"is",@"an",@"array"];
NSArray *numberArray = @[@(1),@(0),@(2),@(3)];
anArray = [self applyOrder:numberArray toArray:anArray];
NSLog(@"%@",anArray);
-(NSMutableArray*)applyOrder:(NSArray *)order toArray:(NSArray *)array
{
NSMutableArray *newArray = [NSMutableArray array];
for(int i =0;i<order.count;i++)
{
[newArray addObject:[array objectAtIndex:[[order objectAtIndex:i]integerValue]]];
}
return newArray;
}
NSNumberas a literal by writing@(theNumber)and you can write anNSArrayas a literal using@[@"this",@"is",@"an",@"array"];which also removes the need tonilterminate the array.