微信发红包,也就是把一个数随机分成n份,n份数额的的值等于总数额。
依据以上规则。实现如下
1.有最小值 其它随机分配
代码实现如下:
- (NSMutableArray *)getRedFromJavaWithTotalMoney:(CGFloat)total redNumber:(NSInteger)number minMoney:(CGFloat)min
{
if(total/number<min)
{
NSLog(@"最小值不合法");
return nil;
}
float money;
double max;
int i=1;
NSMutableArray *math = [NSMutableArray array];
while(i<number)
{
max = total- min*(number- i);
NSInteger k = (int)((number-i)/2);
if (number -i <= 2)
{
k = number -i;
}
max = max/k;
double val = ((double)arc4random() / 0x100000000);
if (max<min)
{
NSLog(@"max小于min");
max = min+1;
}
money=(int)(min*100+val*(max*100-min*100+1));
money=(float)money/100;
total=total-money;
;
[math addObject:[NSString stringWithFormat:@"%f",money]];
// NSLog(@"第%d人 拿到%f",i,money);
i++;
if(i==number)
{
[math addObject:[NSString stringWithFormat:@"%f",total]];
// NSLog(@"最后 第%d人 拿到%f",i,money);
}
}
return math;
}
2.有最小值和最大值
代码实现如下
- (NSMutableArray *)getRedFromJavaWithTotalMoney:(CGFloat)total redNumber:(NSInteger)number minMoney:(CGFloat)min maxMoney:(CGFloat)maxMoney
{
if (total/number>maxMoney)
{
NSLog(@"最大值不合法");
return nil;
}
if(total/number<min)
{
NSLog(@"最小值不合法");
return nil;
}
float money;
double max;
int i=1;
NSMutableArray *math = [NSMutableArray array];
while(i<number)
{
max = total- min*(number- i);
CGFloat canMaxMoney = maxMoney>max?max:maxMoney;
NSInteger k = (int)((number-i)/2);
if (number -i <= 2)
{
k = number -i;
}
max = max/k;
double val = ((double)arc4random() / 0x100000000);
if (max<min)
{
NSLog(@"max小于min");
max = min+1;
}
money=(int)(min*100+val*(canMaxMoney*100-min*100+1));
money=(float)money/100;
total=total-money;
[math addObject:[NSString stringWithFormat:@"%f",money]];
// NSLog(@"第%d人 拿到%f",i,money);
i++;
if(i==number)
{
[math addObject:[NSString stringWithFormat:@"%f",total]];
// NSLog(@"最后 第%d人 拿到%f",i,money);
}
}
return math;
}
好好学习 天天向上
不足之处 欢迎指出
网友评论