RosettaCodeData/Task/Knuths-algorithm-S/Objective-C/knuths-algorithm-s.m

35 lines
757 B
Mathematica
Raw Permalink Normal View History

2013-04-10 22:43:41 -07:00
#import <Foundation/Foundation.h>
typedef NSArray *(^SOfN)(id);
SOfN s_of_n_creator(int n) {
2014-04-02 16:56:35 +00:00
NSMutableArray *sample = [[NSMutableArray alloc] initWithCapacity:n];
2013-04-10 22:43:41 -07:00
__block int i = 0;
2014-04-02 16:56:35 +00:00
return [^(id item) {
2013-04-10 22:43:41 -07:00
i++;
if (i <= n) {
[sample addObject:item];
} else if (rand() % i < n) {
2014-04-02 16:56:35 +00:00
sample[rand() % n] = item;
2013-04-10 22:43:41 -07:00
}
return sample;
2014-04-02 16:56:35 +00:00
} copy];
2013-04-10 22:43:41 -07:00
}
int main(int argc, const char *argv[]) {
2014-04-02 16:56:35 +00:00
@autoreleasepool {
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
NSCountedSet *bin = [[NSCountedSet alloc] init];
for (int trial = 0; trial < 100000; trial++) {
SOfN s_of_n = s_of_n_creator(3);
NSArray *sample;
for (int i = 0; i < 10; i++)
sample = s_of_n(@(i));
[bin addObjectsFromArray:sample];
}
NSLog(@"%@", bin);
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
}
2013-04-10 22:43:41 -07:00
return 0;
}