我正在使用以下方法创建随机数列表
val randomList = List(4) { Random.nextInt(0, 100) }
但是,这种方法不起作用,因为我想避免重复
一种方法是洗牌Range https://kotlinlang.org/docs/reference/ranges.html并获取任意数量的物品:
val randomList = (0..99).shuffled().take(4)
如果范围很大并且您只需要几个数字,那么效率就不那么高了。
在这种情况下,最好使用Set https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html像这样:
val s: MutableSet<Int> = mutableSetOf()
while (s.size < 4) { s.add((0..99).random()) }
val randomList = s.toList()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)