Rajamohan S
Rajamohan S

Reputation: 7269

How to generate random string form array of elements by compared with another array of elements in swift?

I aware to get random character from a string. From here is the code,

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
}

Usage :

var randomArray1 = [String]()

for _ in 0...62{

   randomArray1.append(self.randomString(1))
}

Here, If randomArray1.append(self.randomString(x)), then x = 1...N

Checking repeated elements :

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")

Output:

Same Elements

["_", "u", "8", "7", "E", "P", "u", "y", "C", "-", "C", "x", "l", "j", "t", "D", "U", "2", "e", "2"]

But I need to get array of 62 unique random characters from master by compared with randomArray1. i.e., Array count is zero

How can I achieve this without delay?

Note:

Also, I read this post also I have a answer for shuffling array. But this post different from shuffling only, Please, see usage.

Upvotes: 1

Views: 118

Answers (1)

Mathi Arasan
Mathi Arasan

Reputation: 889

Did you try like this? What I understand from your question. generate a random text where all the characters are unique. Before appending your random string to your array check is array have that char then append into your array.

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)

Output: ["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"]

I tried this with playground. For this output 199 times loop executed.

If anyone knows better than this update yours.

Upvotes: 2

Related Questions