2014-02-08 60 views
-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]); 
     } 
    } 
} 

任何幫助,將不勝感激。謝謝!

回答

2

從我的理解,我認爲這可能是對你有所幫助:

int arrLength = (int)[arrayOfNumbers count]; 
for (int x = 0; x < arrLength/2; x++) { 
    if(x < arrLength-1) { 
     NSLog(@"%i + %i compare %i + %i", [arrayOfNumbers[x] intValue], [arrayOfNumbers[x+1] intValue], [arrayOfNumbers[(arrLength-1) - x] intValue], [arrayOfNumbers[(arrLength-2) - x] intValue]); 
    } 
} 

輸出我得到

2014-02-08 04:36:54.517 Test[54846:70b] (
    3, 
    5, 
    3, 
    6, 
    4, 
    4, 
    6, 
    6, 
    5, 
    6 
) 
2014-02-08 04:36:54.518 Test[54846:70b] 3 + 5 compare 6 + 5 
2014-02-08 04:36:54.519 Test[54846:70b] 5 + 3 compare 5 + 6 
2014-02-08 04:36:54.520 Test[54846:70b] 3 + 6 compare 6 + 6 
2014-02-08 04:36:54.520 Test[54846:70b] 6 + 4 compare 6 + 4 
2014-02-08 04:36:54.521 Test[54846:70b] 4 + 4 compare 4 + 4