Какао Touch - Сравнение Ints - PullRequest
       7

Какао Touch - Сравнение Ints

1 голос
/ 15 августа 2010

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

Есть идеи?

Ответы [ 3 ]

2 голосов
/ 15 августа 2010
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++;
}

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

РЕДАКТИРОВАТЬ:

Для x количества чисел вы можете сделать это (используя 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 голосов
/ 15 августа 2010

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

0 голосов
/ 15 августа 2010

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

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

Редактировать: 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];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...