知乎上看到的java版本的,稍微改了下成OC版本,还不太理解这算法.
过年,微信一个5人的群玩起了5元5个红包,每轮最佳者发下一轮,
好奇,想算下如果2 Vs 3,是2人组 还是 3人组会赚.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
float random100 = (arc4random_uniform(100)+1 );
CGFloat rNum = random100 / 100;
NSLog(@"随机数:%.2f",rNum);
double total_money; // 红包总金额
int total_people; // 抢红包总人数
double min_money; // 每个人最少能收到0.01元
total_money = 5;
total_people = 5;
min_money = 0.01;
for (int i = 0; i < total_people - 1; i++) {
int j = i + 1;
double safe_money = (total_money - (total_people - j) * min_money)
/ (total_people - j);
// NSLog(@"safe_money = %f",safe_money);
double tmp_money = (rNum
* (safe_money * 100 - min_money * 100) + min_money * 100) / 100;
total_money = total_money - tmp_money;
NSLog(@"第 %d 个红包: %.2f 元,剩下: %.2f 元
", j, tmp_money,
total_money);
}
NSLog(@"第 %d 个红包: %.2f 元,剩下: 0 元
", total_people,total_money);
}
return 0;
}