2010-08-15 3 views
1

У меня есть простая проблема. Я собираюсь сгенерировать 3 случайных числа от 0 до 2, и я хочу определить, есть ли дубликаты.Cocoa Touch - Сравнение инд

Любые идеи?

+0

Вы хотите, чтобы тип данных был правильно? Или вы хотите NSInteger? – 2010-08-15 06:31:43

ответ

2
if (num1 == num2) { 
} 
else if (num1 == num3) { 
} 
else if (num2 == num3) { 
} 
else { 
    //There are no dups. 
} 

Проверяет наличие дубликата.

if (num1 == num2) { 
    counter++; 
} 
if (num1 == num3) { 
    counter++; 
} 
if (num2 == num3) { 
    counter++; 
} 

Это находит, сколько дубликатов есть (для дополнительного бонуса).

EDIT:

Для й количества номеров вы можете сделать это (используя 10 в моем примере количества Интса):

int counter = 0; 
int i[10] = { 
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10 
}; 

for (int g = 0; g < 10; g++) 
{ 
    for (int j = g+1; j < 10; j++) 
    { 
     if(i[g] == i[j]) 
     { 
      counter++; 
      printf(@"%d\n", counter); 
      //If this if statement is true then there is a dup... In this case none are found. 
     } 
    } 
} 
+0

Что произойдет, если вы хотите протестировать 10 случайных чисел? Это будет очень долго. –

+0

Brock Woolf: True. Обновленный ответ. :) – 2010-08-15 06:29:16

+0

Редакции не нужны Мне нужно только проверить 3 случайных числа. Но спасибо за усилия! – user377419

0

Как насчет этого?

NSArray *randomNumbers = [[NSArray alloc] initWithObjects:@"0",@"1",@"1",@"2",nil];  
NSMutableDictionary *occurenceDict = [[NSMutableDictionary alloc] init]; 

for (NSString *number in randomNumbers) 
{ 
    if ([occurenceDict objectForKey:number] == nil) { 
     [occurenceDict setValue:[NSNumber numberWithInt:[number intValue]] forKey:number]; 
     int occOfNum = 0; 
     for (int i = 0; i < [randomNumbers count]; i++) { 
      NSString *currentNumber = [randomNumbers objectAtIndex:i]; 
      if ([currentNumber compare:number] == NSOrderedSame) { 
       occOfNum++; 
      } 
     } 
     [occurenceDict setValue:[NSNumber numberWithInt:occOfNum] forKey:number]; 
    } 
} 

for (NSString *key in occurenceDict) { 
    NSString *occurrences = [occurenceDict objectForKey:key]; 
    NSLog(@"Number %d is contained %d times", [key intValue], [occurrences intValue]); 
} 

[randomNumbers release]; 
[occurenceDict release]; 

Выход:

Number 0 is contained 1 times 
Number 1 is contained 2 times 
Number 2 is contained 1 times 

Edit: Incase вы хотите знать, как это работает, вот та же версия, но с комментариями, чтобы помочь вам понять:

// Create array with the numbers that we have randomly generated 
NSArray *randomNumbers = [[NSArray alloc] initWithObjects:@"0",@"1",@"1",@"2",nil];  
NSMutableDictionary *occurenceDict = [[NSMutableDictionary alloc] init]; 

for (NSString *number in randomNumbers) 
{ 
    // If this number has not been added to the dictionary 
    if ([occurenceDict objectForKey:number] == nil) { 
     // Add it 
     [occurenceDict setValue:[NSNumber numberWithInt:[number intValue]] forKey:number]; 
     // Find how many times the number occurs with the "randomNumbers" array 
     int occOfNum = 0; 
     for (int i = 0; i < [randomNumbers count]; i++) { 
      NSString *currentNumber = [randomNumbers objectAtIndex:i]; 
      if ([currentNumber compare:number] == NSOrderedSame) { 
       // We found this number at this index, so increment the found count 
       occOfNum++; 
      } 
     } 
     // Save the number of times which "number" occurs in the dictionary for later 
     [occurenceDict setValue:[NSNumber numberWithInt:occOfNum] forKey:number]; 
    } 
} 

// Iterate through all items in the dictionary and print out the result 
for (NSString *key in occurenceDict) { 
    NSString *occurrences = [occurenceDict objectForKey:key]; 
    NSLog(@"Number %d is contained %d", [key intValue], [occurrences intValue]); 
} 
// Release alloc'ed memory 
[randomNumbers release]; 
[occurenceDict release]; 
0

Крики, эти ответы носят длинный характер! Поместите ваши случайные сгенерированные числа в NSIndexSet. Протестируйте набор перед вставкой числа, и вы узнаете, что номер уже присутствует, а также обман.