Skip to content

Commit 88b2933

Browse files
committed
Fisher-yates implementation in Objective-C
1 parent 3c479a2 commit 88b2933

3 files changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//
2+
// Fisher-yates.h
3+
// Algorithms
4+
//
5+
// Created by intoxicated on 1/4/14.
6+
// Copyright (c) 2014 intoxicated. All rights reserved.
7+
//
8+
9+
#import <Foundation/Foundation.h>
10+
11+
@interface Fisher_yates : NSObject
12+
13+
+ (void)shuffle:(NSMutableArray *)array;
14+
15+
@end
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//
2+
// Fisher-yates.m
3+
// Algorithms
4+
//
5+
// Created by intoxicated on 1/4/14.
6+
// Copyright (c) 2014 intoxicated. All rights reserved.
7+
//
8+
9+
#import "Fisher-yates.h"
10+
11+
@implementation Fisher_yates
12+
13+
+ (void)shuffle:(NSMutableArray *)array
14+
{
15+
int swapIndex;
16+
id temp;
17+
18+
for(int i = (int)array.count - 1; i > 0; --i)
19+
{
20+
swapIndex = arc4random() % i;
21+
22+
temp = [array objectAtIndex:i];
23+
[array replaceObjectAtIndex:i withObject:[array objectAtIndex:swapIndex]];
24+
[array replaceObjectAtIndex:swapIndex withObject:temp];
25+
}
26+
}
27+
28+
@end
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//
2+
// Fisher-Yates_test.m
3+
// Fisher-Yates
4+
//
5+
// Created by intoxicated on 1/4/14.
6+
// Copyright (c) 2014 intoxicated. All rights reserved.
7+
//
8+
9+
#import <Foundation/Foundation.h>
10+
#import "Fisher-yates.h"
11+
12+
int main(int argc, const char * argv[])
13+
{
14+
15+
@autoreleasepool {
16+
17+
NSMutableArray * array = [[NSMutableArray alloc] init];
18+
19+
for (NSInteger i = 0; i < 10; i++)
20+
[array addObject:[NSNumber numberWithInteger:i]];
21+
22+
[Fisher_yates shuffle:array];
23+
24+
NSLog(@"Shuffle result: %@", array);
25+
26+
}
27+
return 0;
28+
}
29+

0 commit comments

Comments
 (0)