码迷,mamicode.com
首页 > 其他好文 > 详细

产生多位随机数

时间:2015-03-21 11:18:47      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:随机数

// 一次产生六个随机数

#define SHU_COUNT 6


//每个随机数的大小范围

#define ALL_NUM 10


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    

    self.window.backgroundColor = [UIColor grayColor];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

    [btn setBackgroundColor:[UIColor purpleColor]];

    [btn addTarget:self action:@selector(actionSuiJi:) forControlEvents:UIControlEventTouchUpInside];

    btn.frame = CGRectMake(0, 0, 200, 40);

    btn.center = self.window.center;

    [self.window addSubview:btn];

    [btn setTitle:@"一次产生多个随机数" forState:UIControlStateNormal];

    

    UITextView  *textView = [[UITextView alloc] init];

    textView.frame = CGRectMake(60, 100, 200, 80);

    textView.tag = 1;

    [textView setFont:[UIFont systemFontOfSize:17]];

    textView.textAlignment = NSTextAlignmentCenter;

    [self.window addSubview:textView];

    

    [self.window makeKeyAndVisible];

    return YES;

}


- (IBAction)actionSuiJi:(id)sender

{

    int z = 0;

    int x = SHU_COUNT;

    NSMutableArray *mutArrGet = [NSMutableArray array];

    for (int i = 0; i < x; i++) {

        z++;

        int b = arc4random()%ALL_NUM+1;

        BOOL isUse = [self compare:mutArrGet andNum:b];

        if (isUse) {

            [mutArrGet addObject:[NSString stringWithFormat:@"%d",b]];

        }else{

            x++;

        }

        if ([mutArrGet count] == SHU_COUNT) break;

    }

    

    UITextView *tv = (UITextView *)[self.window viewWithTag:1];    

    NSMutableString *mutS = [[NSMutableString alloc] init];

    for (NSString *s in mutArrGet) {

        [mutS appendString:s];

        [mutS appendString:@"  "];

    }

    tv.text = mutS;

}



- (BOOL)compare:(NSMutableArray *)mutArr andNum:(int)index

{

    for (NSString *s in mutArr) {

        if (index == [s integerValue]) {

            return NO;

        }

    }

    return YES;

}

技术分享

产生多位随机数

标签:随机数

原文地址:http://blog.csdn.net/tubiebutu/article/details/44513999

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!