Generate random strings using NSArray in iPhone?
I have one array and it has some data. Now i want to randomly changed the positions of the strings which means, want to shuffle the strings into the array. But i don't want to change the order of the array, I want to changed only order the strings and doesn't changed the array index position.
My actual array is (
         (
        first,
        second,
        third,
        fourth
    ),
        (
        One,
        Two,
        Three,
        Four
    ),
        (
        sample,
      开发者_如何学C  test,
        demo,
        data
    )
)
Expected result,
  (
        (
        second,
        fourth,
        third,
        first
    ),
        (
         Two,
         Four,
         One,
         Three
    ),
        (
        test,
        demo,
        sample,
        data
    )
)
Please Help me out.
Thanks!
The NSIndexSet is designed for such tasks.
It's not that hard to do. You should do the following:
Add a category to NSArray. The following implementation is from Kristopher Johnson as he replied in this question.
// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
//  NSMutableArray_Shuffling.m
#import "NSMutableArray_Shuffling.h"
@implementation NSMutableArray (Shuffling)
- (void)shuffle
{
    NSUInteger count = [self count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (arc4random() % nElements) + i;
        [self exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
}
@end
Now you have a method called shuffle, which shuffels your array. Now you can do the following so that only the strings in the inner arrays are shuffled:
for (NSMutableArray *array in outerArray) {
   [array shuffle];
}
Now the inner Arrays are shuffled. But keep in mind, that the inner arrays need to be NSMutableArrays. Else you won't be able to shuffle them. ;-)
Sandro Meier
int randomIndex;
for( int index = 0; index < [array count]; index++ )
{
    randomIndex= rand() % [array count] ;
    [array exchangeObjectAtIndex:index withObjectAtIndex:randomIndex];
}
[array retain];
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论