随机分数题目
2017-11-01 本文已影响40人
CocoaJason
假如有十道题目,每道题目的分数是s,s是随机的(0<= s <= 20),但是十道题目的总分不超过100分。求,十道题目计算完毕,一共是多少分。
do {
NSInteger tempScore = 0;
NSMutableArray *tempAry = [NSMutableArray array];
for (NSInteger idx = 0; idx < 10 ; idx ++)
{
NSInteger s_idx = arc4random() % 21;
tempScore += s_idx;
[tempAry addObject:[NSNumber numberWithInteger:s_idx]];
}
if (tempScore < 100)
{
NSLog(@"%@ total %ld",tempAry,tempScore);
break;
}
} while (true);
打印结果(答案不唯一):
(
6,
19,
1,
12,
17,
3,
14,
1,
20,
5
) total 98
或者
do {
NSMutableArray *tempAry = [NSMutableArray array];
for (NSInteger idx = 0; idx < 10 ; idx ++)
{
NSInteger s_idx = arc4random() % 21;
[tempAry addObject:[NSNumber numberWithInteger:s_idx]];
}
NSNumber *totalScole = [tempAry valueForKeyPath:@"@sum.self"];
if (totalScole.integerValue < 100)
{
NSLog(@"%@ total %@",tempAry,totalScole);
break;
}
} while (true);
使用Swift翻译一下
while true
{
var tempScole = 0
var scoleAry = [Int]()
for _ in 0...10
{
let scale = Int(arc4random()%21)
tempScole += scale
scoleAry.append(scale)
}
if tempScole < 100
{
print("every scole \(scoleAry) and total scole \(tempScole) ")
break;
}
}
while true
{
let scoleAry = NSMutableArray()
for _ in 0...10
{
let scale = Int(arc4random()%21)
scoleAry.add(scale)
}
let totalScole : Int = scoleAry.value(forKeyPath: "@sum.self") as! Int
if totalScole < 100
{
print("every scole \(scoleAry) and total scole \(totalScole) ")
break;
}
}
假如您有更合适的方案,请留言。