Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

【Swift4】 ArrayをShuffleする

Swift4で配列をシャッフルする簡単なサンプルを提示します。
"阿部","伊東","佐藤","鈴木","田中","中村","藤井","松井","村田","吉田"
と五十音順に並んだ人名の配列(anArray)をシャッフルします。

``````var anArray = ["阿部","伊東","佐藤","鈴木","田中","中村","藤井","松井","村田","吉田"]
//shuffle前print
print("shuffle前")
for i in anArray{
print("\(i)")
}
//shuffleする
for i in 0 ..< anArray.count{
let r = Int(arc4random_uniform(UInt32(anArray.count)))
anArray.swapAt(i, r)
}
//shuffle後print
print("shuffle後")
for i in anArray{
print("\(i)")
}
``````

print結果は以下のようになります。

shuffle前

shuffle後

※※追記※※

たかがシャッフル、されどシャッフル 〜"permute-with-all" order biasの検証〜

``````let r = Int(arc4random_uniform(UInt32(anArray.count)))
``````

を以下のように変更します。

``````let r = Int(arc4random_uniform(UInt32(anArray.count - i))) + i
``````

これにより、結果の偏りは無くなります。

``````extension Array{
mutating func shuffle(){
let n = self.count
for i in 0 ..< n{
let r = Int(arc4random_uniform(UInt32(n - i))) + i
self.swapAt(i, r)
}
}
}
``````

``````for i in 0 ..< anArray.count{
let r = Int(arc4random_uniform(UInt32(anArray.count)))
anArray.swapAt(i, r)
}
``````

のプロセスを以下のように2回繰り返すだけでも偏りがなくなります。

``````for _ in 0 ... 1{
for i in 0 ..< anArray.count{
let r = Int(arc4random_uniform(UInt32(anArray.count)))
anArray.swapAt(i, r)
}
}
``````
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
3
Help us understand the problem. What are the problem?