gpt4 book ai didi

ios - 生成随机字母字符串的有效方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:33 29 4
gpt4 key购买 nike

我想要一个随机化的字母表中所有字符的字符串。现在,我创建了一个包含 26 个字符的可变数组,使用 exchangeObjectAtIndex: 方法将它们打乱顺序,然后将每个字符添加到我返回的字符串中。

必须有更好的方法来做到这一点。这是我的代码:

- (NSString *)shuffledAlphabet {
NSMutableArray * shuffledAlphabet = [NSMutableArray arrayWithArray:@[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"]];

for (NSUInteger i = 0; i < [shuffledAlphabet count]; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = [shuffledAlphabet count] - i;
int n = (random() % nElements) + i;
[shuffledAlphabet exchangeObjectAtIndex:i withObjectAtIndex:n];
}

NSString *string = [[NSString alloc] init];
for (NSString *letter in shuffledAlphabet) {
string = [NSString stringWithFormat:@"%@%@",string,letter];
}

return string;
}

最佳答案

这是一个高效的 Fisher-Yates shuffle ,适合您的用例:

- (NSString *)shuffledAlphabet {
NSString *alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// Get the characters into a C array for efficient shuffling
NSUInteger numberOfCharacters = [alphabet length];
unichar *characters = calloc(numberOfCharacters, sizeof(unichar));
[alphabet getCharacters:characters range:NSMakeRange(0, numberOfCharacters)];

// Perform a Fisher-Yates shuffle
for (NSUInteger i = 0; i < numberOfCharacters; ++i) {
NSUInteger j = (arc4random_uniform(numberOfCharacters - i) + i);
unichar c = characters[i];
characters[i] = characters[j];
characters[j] = c;
}

// Turn the result back into a string
NSString *result = [NSString stringWithCharacters:characters length:numberOfCharacters];
free(characters);
return result;
}

关于ios - 生成随机字母字符串的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340974/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com