我试图解决Day14的到来的代码,我得到2660,而不是2640。我做错了什么?我看过其他的解决方案,他们似乎也在遵循同样的方法。http://adventofcode.com/day/14
- (void)day14:(NSArray *)inputs
{
NSMutableDictionary *reindeerDictionary = [[NSMutableDictionary alloc] init];
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\w*) can fly (\\d*) km/s for (\\d*) seconds, but then must rest for (\\d*) seconds." options:0 error:&error];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
if(error) {
NSLog(@"Error in regex formatting:%@", error);
}
for (NSString *input in inputs)
{
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0,input.length)];
for (NSTextCheckingResult *result in matches) {
NSMutableDictionary *reindeer = [[NSMutableDictionary alloc] init];
reindeer[@"speed"] = [f numberFromString:[input substringWithRange:[result rangeAtIndex:2]]];
reindeer[@"flyTime"] = [f numberFromString:[input substringWithRange:[result rangeAtIndex:3]]];
reindeer[@"restTime"] = [f numberFromString:[input substringWithRange:[result rangeAtIndex:4]]];
reindeer[@"points"] = @0;
reindeerDictionary[[input substringWithRange:[result rangeAtIndex:1]]] = reindeer;
}
}
int maxSeconds = 1000;
NSNumber *maxDistanceFlown = @0;
for (int i = 0; i <= maxSeconds; i++) {
for (NSString *reindeerName in reindeerDictionary.allKeys) {
NSMutableDictionary *reindeer = reindeerDictionary[reindeerName];
NSNumber *speed = reindeer[@"speed"];
NSNumber *flyingPeriod = reindeer[@"flyTime"];
NSNumber *restPeriod = reindeer[@"restTime"];
int distanceFlown = [reindeer[@"distanceFlown"] intValue];
int relativeSeconds = i % (restPeriod.intValue + flyingPeriod.intValue);
//Check if going at full speed vs rest
if (relativeSeconds < flyingPeriod.intValue) {
distanceFlown += speed.intValue;
reindeer[@"distanceFlown"] = @(distanceFlown);
NSNumber *distanceFlown = reindeer[@"distanceFlown"];
if (distanceFlown > maxDistanceFlown) {
maxDistanceFlown = distanceFlown;
}
}
}
}
NSLog(@"Part 1: Winning Distance: %@\n",maxDistanceFlown);
}发布于 2016-02-09 07:40:27
我做错了什么?
简单回答:使用迭代(您的for循环迭代超过几秒钟)
稍长一点的答案:
这个问题可以在几行代码中得到解决,而无需任何迭代。这是一个谜,所以没有代码,但一个提示:把循环看作一个单一的苍蝇+休息期。任何旅行时间都将由零或多个完整周期和零个或一个部分周期组成。
HTH
增编
我不相信你的解决方案,虽然过于复杂,却产生了错误的答案。你凭什么认为这是错的?按照问题和结果匹配的例子,运行1000秒的旅行时间。
https://stackoverflow.com/questions/35282838
复制相似问题