2013-07-16 90 views
-1

如何檢查NSArray objectAtIndex中的值不重複?如何檢查NSArray objectAtIndex中的值不重複?

我有兩個整數A和B.兩個都給隨機值。現在我也有int C, C = B - A;我想這些數字在減法後不會重複。

如果結果出現在減法2之後,那麼兩個不會再來。如果2再次出現,那麼我需要進行一些計算並重新生成新的數字,以便給出另一個值而不是2.

我還無法做到這一點。

我試過NSMutableArray並在其中存儲了值,但與之前的值無法比較成功。

這是我在做什麼

int yourInt = C; 

[chk_Array addObject:[NSNumber numberWithInt:yourInt]]; 

int var_Count_chk_Array; 
var_Count_chk_Array = [chk_Array count]; 
NSLog(@"var_Count_chk_Array is: %d",var_Count_chk_Array); 

NSLog(@" check array : %@",chk_Array); 



for (id anObject in chk_Array) { 
    if (anObject == [NSNumber numberWithInt:0]) { 
     // Do something 
     NSLog(@"Catch "); 
    } 
else { 

A = arc4random()% 8; 
NSLog(@"A is: %d",A); 

B = arc4random()% 11; 
NSLog(@"B is: %d",B); 

C = B - A; 
NSLog(@"C is: %d",C); 


lbl_A.text = [NSString stringWithFormat:@"%i",A]; 


if (A>B) { 

    NSLog(@"A is: %d",A); 
    NSLog(@"B is: %d",B); 

    B = B + A + 5; 

    NSLog(@"A is: %d",A); 
    NSLog(@"B is: %d",B); 

    lbl_B.text = [NSString stringWithFormat:@"%i",B]; 


    C = 0; 

    C = B - A; 
    NSLog(@"C is: %d",C); 

    lbl_C.text = [NSString stringWithFormat:@"%i",C]; 
} 
else{ 

    lbl_B.text = [NSString stringWithFormat:@"%i",B]; 

    NSLog(@"C is: %d",C); 
    lbl_C.text = [NSString stringWithFormat:@"%i",C]; 
} 


} 

我只想說減法後的結果來源於先前的一次不同。數字不再來。

任何想法或建議將非常受歡迎。

+0

使用[chk_Array containsObject:[NSNumber number WithInt:yourValue]] 可以幫助你。 –

+3

不好意思說這是重複的。這個問題每週大概會重複兩次。 –

回答

1

檢查這個樣子,

NSArray *USAValues = [[NSArray alloc]initWithObjects:@"1",@"2",@"1", nil]; 

    if([USAValues containsObject:@"9"]){ 
     NSLog(@"already exist"); 
    } 
    else{ 
     NSLog(@"new Value"); 

    } 

編輯:

if([youArray containsObject:newlyGenratedValue]){ 
     NSLog(@"already exist"); 
    } 
    else{ 
     NSLog(@"new Value"); 

    } 
0

您可以使用謂語,它會正常工作。

替代方法是使用NSSet而不是NSArray。每次在NSSet中添加對象時,都必須增加計數。按照Per的定義,它不能保存重複值。 因此重複值不會反映Set中的任何更改。

例如:Set具有{22.34.15},並且您再添加一個值「15」。最終集合將是{22.34.15},所以沒有改變集合。觀察者在計數不增加的情況下,重新執行減法。

希望它有幫助。