我试图从letters
中获取26个中的20个随机值,这些值也必须包含数组name
中的元素。 finalArray
看起来像是:["S", "A", "M", "A", "N", "T", "H", "A", "I", "J", "K", "L", "S", "N", "O","P","Q", "R", "S", "A"]
(随机)
到目前为止:
var letters: [String] = ["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"]
var name: [String] = ["S", "A", "M", "A", "N","T","H","A"]
//Create finalArray elements
var availableLetters = letters.filter { value in
!contains(name, value)
}
var finalArray = availableLetters + name
我试着这样做:
//get 20 objects
var length = name.utf16Count
var beforeArray = finalArray[0...19]
//minus length of the word
var letterCount = beforeArray.count - length
// add missing letters
beforeArray = letters[0...letterCount] + name
这显然是错误的,结果非常不稳定。我可以使用什么作为简单的解决方法?我怎么能实现它?
答案 0 :(得分:2)
从您的示例中可以看出,您想要取name
,然后用字母表中的随机字母右键填充它,长度为20.因为看起来您不介意重复随机字母,这使事情变得容易多了。
棘手的部分是生成一系列n个随机数,最大值。如果你有这个,你可以使用这些数字作为字母数组的索引来选择随机字符。这是生成该序列的一种方法:
// Struct representing a sequence of count
// random numbers in range 0..<max
struct RandomSequence: SequenceType {
let count: Int
let max: Int
func generate() -> GeneratorOf<Int> {
var i = 0
return GeneratorOf {
i++ < self.count
? Int(arc4random_uniform(UInt32(self.max)))
: nil
}
}
}
一旦你有了它,它就可以用来生成填充:
let name = Array("SAMANTHA")
let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
let targetCount = 20
let paddingCount = targetCount - name.count
let ranseq = RandomSequence(count: paddingCount, max: alphabet.count)
let padding = map(ranseq) { alphabet[$0] }
let padded = name + padding
// padded = ["S", "A", "M", "A", "N", "T", "H", "A", "W", "O", "C", "M", "L", "B", "L", "A", "N", "H", "I", "I"]
如果您确实希望随后使用随机字母填入名称,请查看this question的最佳答案。但这可能是最简单的做法,作为上述技术的第二步,而不是尝试将两个步骤结合在一起。
值得注意的是,如果name
是一个字符串,并且您希望结果以字符串形式结束,那么您无需为此方法添加数组:
let name = "SAMANTHA"
let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
let targetCount = 20
let paddingCount = targetCount - count(name)
let ranseq = RandomSequence(count: paddingCount, max: alphabet.count)
let padding = map(ranseq) { alphabet[$0] }
let padded = name + padding
// padded = "SAMANTHASLHMPRDYRHFC"