重複無し乱数
Posted feedbacks - Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #import <Foundation/Foundation.h>
@interface NSArray (Bingo)
+ (NSArray*)bingo:(int)n;
@end
@implementation NSArray (Bingo)
+ (NSArray*)bingo:(int)n
{
NSMutableArray* array = [NSMutableArray array];
int i;
for (i=1; i<=n; i++) [array addObject:[NSNumber numberWithInteger:i]];
NSMutableArray* result = [NSMutableArray array];
for (i=1; i<=n; i++) {
int size = n - i + 1;
int index = rand() % size;
[result addObject:[array objectAtIndex:index]];
[array removeObjectAtIndex:index];
}
return result;
}
@end
int main(int argc, char** argv)
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];
srand(time(0));
NSLog(@"%@", [NSArray bingo:3]);
NSLog(@"%@", [NSArray bingo:10]);
[pool release];
return 0;
}
|


raynstard
#3402()
Rating0/0=0.00
このお題はraynstardさんの投稿を元にしています。ご投稿ありがとうございました。 投稿の内容には表示のしかたも含まれていたのですが、 このお題では「重複しない1~nまでの乱数をどうやって作るか」という点に集中することにして、 結果の整形は続編としてこの後のお題で出すことにします。 サンプル入出力は下のようになります。
[ reply ]