SORU
3 HAZİRAN 2014, Salı


Ne kadar Hızlı bir dizi karışık mı?

Nasıl ya Swift bir dizi içindeki elemanları rastgele shuffle mı? Eğer benim dizisi 52 karttan oluşur, örneğin, "" desteyi karıştırır. için diziyi karıştırmak istiyorum

CEVAP
4 HAZİRAN 2014, ÇARŞAMBA


Hızlı 2.0

Herhangi bir koleksiyon türü için Fisher-Yates () hızlı ve düzgün bir shuffle ekleyebilirsiniz. Adlandırma ve davranış Swıft 2.0 sort() takip sortInPlace() yöntem:

extension CollectionType where Index == Int {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    }
}

extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        if count < 2 { return }

        for i in 0..<count - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i)))   i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

[1, 2, 3].shuffle()
// [2, 3, 1]

let fiveStrings = 0.stride(through: 100, by: 5).map(String.init).shuffle()
// ["20", "45", "70", "30", ...]

var numbers = [1, 2, 3, 4]
numbers.shuffleInPlace()
// [3, 2, 1, 4]

Swift 1.2

Burada Fisher-Yates () hızlı ve düzgün bir shuffle ekleme üç farklı yolu vardır.

Bir fonksiyonu olarak shuffle

Bu basit versiyonubu işlev her yerde en üst düzeyde Ekle ve Karıştır diziler ve dilimlere mümkün olacak:

func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
    let c = count(list)
    if c < 2 { return list }
    for i in 0..<(c - 1) {
        let j = Int(arc4random_uniform(UInt32(c - i)))   i
        swap(&list[i], &list[j])
    }
    return list
}
shuffle([1, 2, 3, 4, 5, 6, 7, 8])        // e.g., [6, 1, 8, 3, 2, 4, 7, 5]
shuffle(["hello", "goodbye", "ciao"])    // e.g., ["ciao", "goodbye", "hello"]

Mutasyona dizi bir yöntem olarak shuffle

Bu uzantısı Array örnek bir değişken shuffle yerde izin verir:

extension Array {
    mutating func shuffle() {
        if count < 2 { return }
        for i in 0..<(count - 1) {
            let j = Int(arc4random_uniform(UInt32(count - i)))   i
            swap(&self[i], &self[j])
        }
    }
}
var numbers = [1, 2, 3, 4, 5, 6, 7, 8]
numbers.shuffle()                     // e.g., numbers == [6, 1, 8, 3, 2, 4, 7, 5]

Olmayan mutasyona dizi bir yöntem olarak shuffled

Bu uzantısı Array örnek almak karıştırılan bir kopyasını izin verir:

extension Array {
    func shuffled() -> [T] {
        if count < 2 { return self }
        var list = self
        for i in 0..<(list.count - 1) {
            let j = Int(arc4random_uniform(UInt32(list.count - i)))   i
            swap(&list[i], &list[j])
        }
        return list
    }
}
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let mixedup = numbers.shuffled()     // e.g., mixedup == [6, 1, 8, 3, 2, 4, 7, 5]

this gist kopyala-pastable daha fazla bir biçimde tüm bu alabilirsiniz.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • expertvillage

    expertvillag

    5 NİSAN 2006
  • K-391

    K-391

    23 EKİM 2012
  • Marina and The Diamonds

    Marina and T

    8 Temmuz 2008