1

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,
        test,
        demo,
        data
    )
)

Expected result,

  (
        (
        second,
        fourth,
        third,
        first
    ),
        (
         Two,
         Four,
         One,
         Three
    ),
        (
        test,
        demo,
        sample,
        data
    )
)

Please Help me out.

Thanks!

Pugalmuni
  • 9,350
  • 8
  • 56
  • 97

3 Answers3

1

The NSIndexSet is designed for such tasks.

Joe
  • 56,979
  • 9
  • 128
  • 135
1

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

Community
  • 1
  • 1
Sandro Meier
  • 3,071
  • 2
  • 32
  • 47
0

int randomIndex;

for( int index = 0; index < [array count]; index++ )
{
    randomIndex= rand() % [array count] ;

    [array exchangeObjectAtIndex:index withObjectAtIndex:randomIndex];
}
[array retain];
Rams
  • 1,721
  • 12
  • 22