2009-11-03 12 views
0

L'objectif est de générer une longueur de caractères NSString et d'affecter chaque chaîne à un tableau. Je suis coincé sur ce que j'ai besoin de faire avec mon algorithme pour obtenir le bon résultat. Voici l'exemple. Le résultat que je reçois est la même chaîne générée aléatoirement ajoutée à mon tableau 26 fois au lieu de 26 chaînes DIFFÉRENTES ajoutées.Algorithme permettant d'ajouter des NSStrings générés aléatoirement à NSMutableArray

J'ai pensé à déclarer 26 NSStrings différents et à affecter chaque résultat de l'algorithme à chaque chaîne, mais cela semble inefficace. Merci pour l'aide.

NSMutableString *string = @"expert"; 
NSUInteger strLength = [string length]; 
NSString *letterToAdd; 
NSString *finishedWord; 
NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength]; 
NSMutableArray *randomArray = [[NSMutableArray alloc] init]; 

NSArray *charArray = [[NSArray alloc] initWithObjects: @"a", @"b", @"c", @"d", 
         @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", 
         @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", 
         @"x", @"y", @"z", nil]; 

for (int a = 0; a < 26; a++) { 
    for (int i = 0; i < strLength; i++) { 

    letterToAdd = [charArray objectAtIndex: arc4random() % [charArray count]]; 
    if([randomString length] < strLength) { 
     [randomString insertString: letterToAdd atIndex: i]; 
    } 

    finishedWord = randomString; 
    } 

    [randomArray addObject: finishedWord]; 
} 

NSLog(@"Random Array count %i, contents: %@", [randomArray count], randomArray); 

Répondre

1

Vous devez créer une nouvelle randomString à chaque fois:

NSMutableString *string = @"expert"; 
NSUInteger strLength = [string length]; 
NSString *letterToAdd; 
NSString *finishedWord; 
//NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength]; 
NSMutableArray *randomArray = [[NSMutableArray alloc] init]; 

NSArray *charArray = [[NSArray alloc] initWithObjects: @"a", @"b", @"c", @"d", @"e", @"f", 
         @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"o", @"p", @"q", @"r", @"s", 
         @"t", @"u", @"v", @"w", @"x", @"y", @"z", nil]; 

for (int a = 0; a < 26; a++) { 
    NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength]; 

    for (int i = 0; i < strLength; i++) { 

      letterToAdd = [charArray objectAtIndex: arc4random() % [charArray count]]; 
       //if([randomString length] < strLength) { 
        [randomString insertString: letterToAdd atIndex: i]; 
       //} 

     //finishedWord = randomString; 
    } 

    //[randomArray addObject: finishedWord]; 
    [randomArray addObject: randomString]; 
} 

NSLog(@"Random Array count %i, contents: %@", [randomArray count], randomArray); 
+0

a bien fonctionné, merci! –

0

Vous ajoutez le même objet à votre tableau à chaque fois dans la boucle et l'écrasez au fur et à mesure. Vous avez dit:

J'ai pensé à déclarer 26 différentes NSStrings et attribuer chaque résultat de l'algorithme à chaque chaîne ...

Et c'est en effet exactement ce que vous devez faire. Déplacer l'initialisation de randomString dans la boucle résoudra votre problème (obtenir un nouveau NSMutableString à chaque itération de boucle, plutôt que d'utiliser un seul objet). Modifier la définition de randomString à une définition de type simple:

NSMutableString *randomString; 

puis dans votre boucle extérieure, ajoutez cette ligne:

randomString = [NSMutableString stringWithCapacity:strLength]; 

Vous ne devriez pas avoir besoin de changer tout le reste de votre code .

2

Voilà comment je le ferais:

#import "NSString+Shuffle.h" 
NSString * string = @"expert"; 
NSUInteger strLength = [string length]; 
NSString * alphabet = @"abcdefghijklmnopqrstuvwxyz"; 
NSMutableSet * randomWords = [NSMutableSet set]; 

while ([randomWords count] < 26) { 
    NSString * newWord = [alphabet shuffledString]; 
    newWord = [newWord substringToIndex:strLength]; 
    [randomArray addObject:newWord]; 
} 
NSLog(@"Random set count %d, contents: %@", [randomWords count], randomWords); 

Vous auriez alors besoin d'une catégorie sur NSString qui définit shuffledString. Cette méthode prendrait simplement les caractères dans la chaîne et les réorganiserait aléatoirement. Les algorithmes de shuffle décent peuvent être trouvés assez facilement avec Google.

J'espère que vous aurez l'idée de base de comment cela fonctionne. La seule modification que j'ai faite est d'utiliser un NSSet au lieu d'un NSArray, et ce qui est conditionnel à la boucle. L'élimine la possibilité (mince) de mots aléatoires en double.

Edit: depuis que je me sens généreux, voici une shuffledString base mise en œuvre:

//NSString+Shuffle.h 
@interface NSString (ShuffleAdditions) 

- (NSString *) shuffledString; 

@end 

//NSString+Shuffle.m 
#import "NSString+Shuffle.h" 

@implementation NSString (ShuffleAdditions) 

- (NSString *) shuffledString { 
    NSMutableString * shuffled = [self mutableCopy]; 
    NSUInteger length = [shuffled length]; 
    for (int i = 0; i < (4*length); ++i) { 
    NSString * randomChar = [shuffled subStringWithRange:NSMakeRange(arc4random() % (length-1), 1)]; 
    [shuffled appendString:randomChar]; 
    } 
    return [shuffled autorelease]; 
} 
@end 
+0

Pour des performances encore plus rapide, utilisez un 'char * 'de l'alphabet, et mélangez * cela *. Puis construisez un 'NSString' en utilisant le' char * ' –

+2

Cela fait beaucoup d'indexation dans la chaîne à mélanger, entre autres choses. Je pense que créer une méthode de catégorie sur NSString est un peu lourd pour le besoin. C'est le bon moment pour écrire une fonction C simple, utilisez un char (statique) pour contenir la chaîne source et un autre pour écrire, puis créez et renvoyez un NSString (+ stringWithUTF8String :) avec le contenu du null. chaîne C aléatoire terminée. Rapide et facile, et minimise les appels Objective-C pour quelque chose qui n'en a pas besoin, pour démarrer. –

+0

Merci pour la stratégie différente. Très utile. –