0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

条件付きでシャッフル

Posted at

条件付きで配列を入れ替える方法です。

val fruitList:MutableList<String> = mutableListOf("りんご", "もも", "さくらんぼ", "栗", "みかん")
val shuffleList = fruitList.shuffled()
println(shuffleList) // [みかん, りんご, 栗, もも, さくらんぼ]

shuffled()を使用します。

val fruitList: MutableList<String> = mutableListOf("りんご", "もも", "さくらんぼ", "栗", "みかん") 
var shuffleResults: List<String>?

do {
    val shuffleList = fruitList.shuffled()
    shuffleResults = shuffleList
} while (fruitList.indices.any { fruitList[it] == shuffleList[it] })
    
println(shuffleResults) // [もも, さくらんぼ, 栗, みかん, りんご]

while文を使用して、条件が合わなくなるまでシャッフルを行います。配列の位置に同じ果物がある場合、再度シャッフルを行うコードです。

val previousResults = listOf("もも", "さくらんぼ", "栗", "みかん", "りんご")
val fruitList = mutableListOf("りんご", "もも", "さくらんぼ", "栗", "みかん")
var shuffleResults: List<String>?

do {
    val shuffleList = fruitList.shuffled()
    shuffleResults = shuffleList
} while (fruitList.indices.any { shuffleList[it] == previousResults[it] })

println(shuffleResults) // [りんご, みかん, もも, さくらんぼ, 栗]

上記コードを少し変えて、前回の結果と同じにならないようにするコードです。previousResultsはメモリに保存しておいた前回のコードを想定しています。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?