我知道从字符串中获取随机字符。来自here的是代码,
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
用法:
var randomArray1 = [String]()
for _ in 0...62{
randomArray1.append(self.randomString(1))
}
此处,如果randomArray1.append(self.randomString(x))
,则x = 1...N
检查重复元素:
var sameElementCatcher = [String]()
for x in 0...62{
let element = randomArray1[x]
randomArray1[x] = ""
if randomArray1.contains(element){
sameElementCatcher.append(element)
}
}
print("Same Elements")
print(sameElementCatcher.count != 0 ? sameElementCatcher : "Array count is zero")
输出:
相同元素
[" _"," u"," 8"," 7"," E",& #34; P"," u"," y"," C"," - "," C& #34;," x"," l"," j", " t"," D"," U"," 2"," e"," 2& #34;]
但与master
相比,我需要从randomArray1
获取62个唯一随机字符数组。即,数组计数为零
如何立即实现这一目标?
注意:
答案 0 :(得分:2)
generate a random text where all the characters are unique
。
在将随机字符串附加到数组之前,检查数组是否有char
然后附加到数组中。
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
var randomArray1 = [String]()
var tempRandomString = ""
let totalRandomCount = 62
var randomArrayCount = 0
while (totalRandomCount > randomArrayCount) {
tempRandomString = randomString(1)
if !randomArray1.contains(tempRandomString) {
randomArray1.append(tempRandomString)
randomArrayCount+=1
}
}
print(randomArray1)
输出:["X", "u", "j", "1", "n", "E", "D", "q", "U", "6", "T", "O", "f", "J", "i", "c", "W", "V", "G", "R", "k", "7", "_", "8", "-", "l", "w", "4", "e", "Q", "C", "m", "M", "Y", "o", "S", "B", "2", "Z", "P", "p", "N", "y", "H", "a", "h", "z", "s", "b", "A", "3", "g", "x", "L", "v", "F", "d", "r", "t", "K", "9", "5"]
我在操场上试过这个。对于此输出执行199
次循环。
如果有人知道比你的更新更好。