索引后随机排列数组
shuffle array after index
我正在尝试在特定索引后打乱数组,我使用 splitting/joined 机制,但是,有什么有效的方法吗?
例如:
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]
shuffle()
是MutableCollection
协议的一个方法,因此它可以应用于数组切片。示例:
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]
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 array
的随机副本
我正在尝试在特定索引后打乱数组,我使用 splitting/joined 机制,但是,有什么有效的方法吗?
例如:
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]
shuffle()
是MutableCollection
协议的一个方法,因此它可以应用于数组切片。示例:
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]
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 array