-2
我寫了一個算法,我希望它使用隨機數字數組並在該數組中添加第一個和最後一個數字。例如:我的數組是[0,5,3,8,2,4,7,9,6,1],我的算法應該檢查1 + 5 = 6 + 0,因爲它不是,它應該檢查是否5 + 3 = 9 + 6,那麼如果3 + 8 = 7 + 9,依此類推......如何更改for循環外的int
我的第一個for循環是數組中最後一個數字被檢查的地方。問題是int totalOfLastValues
只是在for循環中更新,所以最後的值甚至沒有增加。例如,在數組[0,5,3,8,2,4,7,9,6,1]中,0 + 5 = 6 + 1不是真的,所以它檢查5 + 3 = 6 + 1而不是檢查5 + 3 = 9 + 6。
在我.h
@interface FirstViewController : UIViewController
@end
int totalOfLastValues;
int end;
int almost;
在我.m
-(void) numberAlgorithm {
NSMutableArray *arrayOfNumbers = [NSMutableArray array];
for (int x = 0; x < 10; x++)
{
int randomNumbers = arc4random_uniform(10);
[arrayOfNumbers addObject: [NSNumber numberWithInteger: randomNumbers]];
}
NSLog(@"%@",arrayOfNumbers);
int lastValue = [arrayOfNumbers count]-1;
for (int p = lastValue; p > 2; p--) {
end = [arrayOfNumbers[0 + p] integerValue];
almost = [arrayOfNumbers[(0-1) + p] integerValue];
totalOfLastValues = end + almost;
}
int mostRecentValue = [arrayOfNumbers[0] integerValue];
for (int i = 1; i < [arrayOfNumbers count]-2; i++) {
int one = mostRecentValue;
int two = [arrayOfNumbers[i] integerValue];
mostRecentValue = two;
if ((one + two) == totalOfLastValues) {
NSLog(@"2: Because %@ + %@ = %@ + %@",arrayOfNumbers[i-1],arrayOfNumbers[i],arrayOfNumbers[(0-1) + lastValue],arrayOfNumbers[0 + lastValue]);
break;
} else {
NSLog(@"-1: Because %@ + %@ != %@ + %@",arrayOfNumbers[i-1],arrayOfNumbers[i],arrayOfNumbers[(0-1) + lastValue],arrayOfNumbers[0 + lastValue]);
}
}
}
任何幫助,將不勝感激。謝謝!