IOS 一些簡單的數字隨機算法 去重等功能 – iPhone手機開發技術文章 iPhone軟體開發教學課程

小弟不才在開發過程中使用到瞭一些簡單的隨機數在做一些彩票的應用可以使用到 如有更好的希望觀看此文章的進行分享

– (NSMutableArray *)rulesBallCount:(Rules)rules
{
NSMutableArray *array = [[NSMutableArray alloc] init];

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

[array addObject:[NSString stringWithFormat:@”%d”,i]];
}
return array;
}

/**
@功能: 生成隨機號碼
@參數: count 要隨機幾註
@返回值: 返回生成的數組
*/
– (NSArray *)randomBallNumber:(Rules)rules Count:(NSInteger)count
{
NSMutableArray *arrayNumber = [self rulesBallCount:rules];

NSMutableArray *array = [[NSMutableArray alloc] init];

// ============================
// 基本隨機
// ============================

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

int countn = [arrayNumber count];

NSMutableArray *ar = [[NSMutableArray alloc] initWithArray:arrayNumber];
//存儲每一行的球號
NSMutableArray *ballArray = [[NSMutableArray alloc] init];

for (int k = 0; k < 7; k++) {

int index = arc4random()%countn;

[ballArray addObject:[ar objectAtIndex:index]];
[ar removeObjectAtIndex:index];
countn–;
}
[ar release];

//當數組個數為0的時候直接添加隨即球
if ([array count] == 0) {

[array addObject:ballArray];
}else
{
//驗證球是否重復
int pcount = [array count];

//當變量等於yes時想數組裡添加球號數組
BOOL qbool = YES;
for (int q = 0 ; q < pcount; q++) {

NSArray *resultArrayj = [[array objectAtIndex:q] sortedArrayUsingSelector:@selector(compare:)];
NSString *jsonj = [StaticTools arrayToJsonString:resultArrayj];

NSArray *resultArrayl = [ballArray sortedArrayUsingSelector:@selector(compare:)];
NSString *jsonball = [StaticTools arrayToJsonString:resultArrayl];
if ([jsonj isEqualToString:jsonball]) {

i–;
qbool = NO;
}

}
if (qbool == YES)
{
[array addObject:ballArray];
}
}

[ballArray release];

}

return [array autorelease];
}

/**

函數功能:

把一個數組轉換為一個Json格式的字符串

參數說明:

array:需要進行轉換的數組

返回值:

json格式的字符串

*/

+ (NSString *)arrayToJsonString:(NSArray *)array

{

CJSONSerializer *serializer = [[CJSONSerializer alloc] init];

NSString *jsonString = [serializer serializeArray:array]; //
把字典參數格式化為json格式的字符串

[serializer release];

return jsonString;

}

發佈留言