如何总共使用10个字符并确保随机使用4个不同集合中的至少一个字符 [英] How to have 10 characters total and make sure at least one character from 4 different sets is used randomly
问题描述
我有一个文本字段和一个生成随机字符集的按钮。设置1 =小写,设置2 =大写,设置3 =数字,设置4 =符号
I have a text field and a button that generates a random set of characters. Set 1 = lowercase, set 2 = uppercase, set 3 = numbers, set 4 = symbols
我希望按钮生成的字符数不少于10个,并且最少
I want the the button to generate no more no less that 10 characters and minimum pull from each of the sets at least once.
到目前为止,我的想法是
My idea of how to do it so far is
let roomIDGenerated = uniqueRoomID.text
let roomIDCount = roomIDGenerated?.characters.count
let randomCharacterSet = arc4random() upp
while roomIDCount < 10 {
<#code#>
}
但是我不知道该怎么做...我不知道t总是希望前4个字符始终是每个字符。.也许最后使用了一组必需的字符。
But I don't see how to do it...i don't always want the first 4 characters to always be one of each.. maybe one of the required sets is used last.
我有点卡住了,任何帮助将不胜感激
I'm kinda stuck in general, any help would be appreciated
推荐答案
马丁评论了我采用的相同方法。这是我的实现:
Martin commented with the same approach I was taking. Here is my implementation:
extension CollectionType {
var random: Generator.Element {
guard !isEmpty else { fatalError("array cannot be empty") }
let array = Array(self)
return array[Int(arc4random_uniform(UInt32(array.count)))]
}
}
// from http://stackoverflow.com/a/24029847/1223781
extension MutableCollectionType where Index == Int {
func shuffled() -> Self {
var copy = self
copy.shuffle()
return copy
}
mutating func shuffle() {
guard count >= 2 else { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
let sets = ["abc", "ABC", "123", "#$%"].map { Array($0.characters) }
let size = 10
var randoms = sets.map { $0.random }
while randoms.count < 10 {
randoms.append(sets.random.random)
}
print(randoms.shuffled()) // ["b", "b", "3", "c", "#", "%", "A", "#", "1", "%"]
这篇关于如何总共使用10个字符并确保随机使用4个不同集合中的至少一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!