You might be looking for this sort of thing. Let's get rid of random
and just shuffle arr
to generate a list of actual values in random order. (There's lots of array-shuffling code on Stack Overflow so I won't bother to tell you how to do that.) Then we can also get rid of your intermediate arrays and just deal directly into the inner arrays of the array-of-arrays groups
:
var groups : [[String]] = Array(repeating: [], count: 5)
var shuffled = ["hey", "ho", "nonny", "no", "sis", "boom", "bah", "yo", "hi", "lo"]
var next = 0
for ix in stride(from:0, to:9, by:2) {
for ixx in 0..<2 {
groups[next].append(shuffled[ix+ixx])
}
next += 1
}
groups // [["hey", "ho"], ["nonny", "no"], ["sis", "boom"], ["bah", "yo"], ["hi", "lo"]]
We can actually express that more concisely using map
(as explained Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?):
let shuffled = ["hey", "ho", "nonny", "no", "sis", "boom", "bah", "yo", "hi", "lo"]
let chunkSize = 2
let groups = stride(from: 0, to: shuffled.count, by: chunkSize).map {
Array(shuffled[$0..<min($0 + chunkSize, shuffled.count)])
}
groups // [["hey", "ho"], ["nonny", "no"], ["sis", "boom"], ["bah", "yo"], ["hi", "lo"]]
Even better, we can make this an extension on Array:
extension Array {
func chunked(by chunkSize:Int) -> [[Element]] {
let groups = stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0..<[$0 + chunkSize, self.count].min()!])
}
return groups
}
}
let shuffled = ["hey", "ho", "nonny", "no", "sis", "boom", "bah", "yo", "hi", "lo"]
let groups = shuffled.chunked(by:2)
groups // [["hey", "ho"], ["nonny", "no"], ["sis", "boom"], ["bah", "yo"], ["hi", "lo"]]