2015-09-21 8 views
9

Ho questa estensione che creerà un nuovo array che hanno gruppo di matrici a caso dal dato array:errore fatale: scambiando un luogo con se stesso non è supportato con Swift 2.0

extension Array { 
    var shuffle:[Element] { 
     var elements = self 
     for index in 0..<elements.count { 
      swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count-index)))+index ]) 
     } 
     return elements 
    } 
    func groupOf(n:Int)-> [[Element]] { 
     var result:[[Element]]=[] 
     for i in 0...(count/n)-1 { 
      var tempArray:[Element] = [] 
      for index in 0...n-1 { 
       tempArray.append(self[index+(i*n)]) 
      } 
      result.append(tempArray) 
     } 

     return result 
    } 
} 

E io sto usando come questo:

let mainArr = Array(1...60) 
let suffeldArr = mainArr.shuffle.groupOf(10) 
print(suffeldArr) 

E stamperà come:

[[10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60], [10 random element between 1 to 60]] 

Ma mi sta dando un errore in fase di esecuzione tim e in questa linea:

swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count-index)))+index ]) 

che dice:

fatal error: swapping a location with itself is not supported

Si stava lavorando bene in 1.2, ma ora non sta funzionando in 2.0.

Non so come risolvere questo.

+0

Nota che il codice in http://stackoverflow.com/a/24029847/1187415 è stato aggiornato per risolvere questo problema: http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in -swift/24029847 # comment52863556_24029847 –

+0

Grazie ... @MartinR –

risposta

11

Si sta cercando di scambiare un elemento con se stesso, è necessario eseguire un controllo per vedere se non si sta cercando di scambiare un elemento allo stesso punto nella matrice, in questo modo:

extension Array { 
    var shuffle:[Element] { 
     var elements = self 
     for index in 0..<elements.count { 
      let newIndex = Int(arc4random_uniform(UInt32(elements.count-index)))+index 
      if index != newIndex { // Check if you are not trying to swap an element with itself 
       swap(&elements[index], &elements[newIndex]) 
      } 
     } 
     return elements 
    } 
    func groupOf(n:Int)-> [[Element]] { 
     var result:[[Element]]=[] 
     for i in 0...(count/n)-1 { 
      var tempArray:[Element] = [] 
      for index in 0...n-1 { 
       tempArray.append(self[index+(i*n)]) 
      } 
      result.append(tempArray) 
     } 

     return result 
    } 
} 
+0

Sì, funziona! Grazie per l'aiuto .. :) –

+0

@DharmeshKheni controlla anche questa risposta per un algoritmo semplice e pulito di Fisher-Yates: http://stackoverflow.com/a/24029847/1009013 – vrwim

+0

sì Martin ha già suggerito che .. :) –

Problemi correlati