fisher-yates


See On Github

Data

Tags

shuffle

Source Code

//
//  Fisher-yates.h
//  Algorithms
//
//  Created by intoxicated on 1/4/14.
//  Copyright (c) 2014 intoxicated. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Fisher_yates : NSObject

+ (void)shuffle:(NSMutableArray *)array;

@end
//
//  Fisher-yates.m
//  Algorithms
//
//  Created by intoxicated on 1/4/14.
//  Copyright (c) 2014 intoxicated. All rights reserved.
//

#import "Fisher-yates.h"

@implementation Fisher_yates

+ (void)shuffle:(NSMutableArray *)array
{
    int swapIndex;
    id temp;
    
    for(int i = (int)array.count - 1; i > 0; --i)
    {
        swapIndex = arc4random() % i;
        
        temp = [array objectAtIndex:i];
        [array replaceObjectAtIndex:i withObject:[array objectAtIndex:swapIndex]];
        [array replaceObjectAtIndex:swapIndex withObject:temp];
    }
}

@end
//
//  Fisher-Yates_test.m
//  Fisher-Yates
//
//  Created by intoxicated on 1/4/14.
//  Copyright (c) 2014 intoxicated. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Fisher-yates.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSMutableArray * array = [[NSMutableArray alloc] init];
        
        for (NSInteger i = 0; i < 10; i++)
            [array addObject:[NSNumber numberWithInteger:i]];
        
        [Fisher_yates shuffle:array];
        
        NSLog(@"Shuffle result: %@", array);

    }
    return 0;
}