代码之家  ›  专栏  ›  技术社区  ›  SPatel mash

索引后洗牌数组

  •  0
  • SPatel mash  · 技术社区  · 7 年前

    我尝试在特定索引之后洗牌数组,我使用了拆分/加入机制,但是,有没有有效的方法?

    前任:

    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]
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   Martin R    7 年前

    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]
    
        2
  •  2
  •   Rizwan    7 年前
    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数组的无序副本

    推荐文章