algorithme pour ajouter NSStrings au hasard générés à NSMutableArray
-
13-09-2019 - |
Question
Le but est de générer un caractère NSString de longueur et attribuer à chaque chaîne à un tableau. Je suis en train coincé sur ce que je dois faire avec mon algorithme pour obtenir le résultat correct. Voici l'échantillon. Le résultat que je reçois est la même chaîne aléatoire ajouté à mon tableau 26 fois au lieu de 26 chaînes différentes ajoutées.
J'ai pensé à déclarer 26 différentes NSStrings et attribuer 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);
La solution
Vous devez créer un nouveau 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);
Autres conseils
Voici 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 serait tout simplement prendre les caractères de la chaîne et les réorganiser au hasard. Les algorithmes de lecture aléatoire décent peuvent être trouvés facilement avec Google.
J'espère que vous avez l'idée de base de la façon dont cela fonctionne. La seule modification que je fait utilise un NSSet au lieu d'un NSArray, et ce que la condition de la boucle est. La possibilité élimine la (mince) de double mots aléatoires.
Edit: depuis que je me sens généreux, voici une implémentation shuffledString
de base:
//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
Vous ajoutez le même objet à votre tableau chaque fois dans la boucle, et les écrasera comme vous allez. Vous avez mentionné:
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éplacement de l'initialisation de randomString
dans la boucle résoudra votre problème (obtenir un nouveau NSMutableString
à chaque itération de la 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.