我正在尝试在特定索引之后改组数组,我使用了拆分/联合机制,但是有什么有效的方法吗?
例如:
var arr = [0,1,2,3,4,5,6,7,8,9]
arr.shuffle(after index:4)
print(arr) -> //[0,1,2,3,4,7,9,8,6]
arr.shuffle(after index:0)
print(arr) -> //[0,3,2,1,4,9,8,6,8]
答案 0 :(得分:4)
shuffle()
是MutableCollection
协议的一种方法,因此可以将其应用于数组 slice。示例:
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arr[5...].shuffle() // Shuffle elements from index 5 to the end
print(arr) // [0, 1, 2, 3, 4, 6, 8, 7, 5, 9]
答案 1 :(得分:2)
extension Array {
mutating func shuffle(fromIndex:Int) {
self[fromIndex...].shuffle()
}
func shuffled(fromIndex:Int) -> [Element]{
return self[..<fromIndex] + self[fromIndex...].shuffled()
}
}
var arr = [0,1,2,3,4,5,6,7,8,9]
arr.shuffle(fromIndex: 4) // 0,1,2,3,x,x,x,x,x,x - x - any of the value of 4...9
let arr2 = [0,1,2,3,4,5,6,7,8,9]
var arr3 = arr2.shuffled(fromIndex: 4)
要使mutating func shuffle(fromIndex:Int)
工作,数组必须为var
。这不适用于let
。 func shuffled(fromIndex:Int) -> [Any]
-用于随机组合的let数组