如何通过与swift中的另一个元素数组进行比较来生成随机字符串形式的元素数组?

时间:2017-08-07 06:47:49

标签: arrays swift swift3

我知道从字符串中获取随机字符。来自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个唯一随机字符数组。即,数组计数为零

如何立即实现这一目标?

注意:

另外,我也读了this帖子,我也有一个answer用于改组数组。但这篇文章不同于改组,请参阅usage

1 个答案:

答案 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次循环。

如果有人知道比你的更新更好。