【问题标题】:How to create random list without repeating one previous value? [closed]如何在不重复前一个值的情况下创建随机列表? [关闭]
【发布时间】:2019-12-31 11:38:16
【问题描述】:

This 代码创建随机数列表,但有时前一个索引的值会重复。我可以使用下面的代码来避免重复,但它会创建随机整数,而不是列表。所以,我需要避免列表像这样[1,1,0,5],并希望它像这样[1,0,1,5]

var previousIndex = 0

private fun getNewRandomIndex(): Int {
        var newIndex = -1
        while (true) {
            newIndex = random.nextInt(randomValues.size)
            if (previousIndex != newIndex) {
                previousIndex = newIndex
                break
            }
        }
        return newIndex
    }

我想为此代码使用名为 randomNumbers 的已创建列表。

var lastIndex = 0
 imageView.setOnClickListener {


                lastIndex = (lastIndex + 1) % randomNumbers.size
            button.text = randomNumbers[lastIndex].toString()
        }

已编辑:

var lastIndex = 0
    val set = mutableSetOf<Int>()
            while (set.size < 5) {
                set.add(getNewRandomIndex())
            }
            set.toList()

    imageView.setOnClickListener {
                    lastIndex = (lastIndex + 1) % set.size
                button.text = set[lastIndex].toString()
            }

    Error: No get method providing array access

【问题讨论】:

  • 您只是不想两次相同的值?使用你拥有的代码,记住最后一个值,如果下一个出现,忽略它,获取下一个随机数,直到它与输出的最后一个不同。
  • 感谢您的评论,我想通过在测验前预先检查和预设值来找到解决测验应用程序延迟问题的方法(请参阅链接帖子)。
  • 避免重复的一种方法是随机播放,而不是随机选择。

标签: android list kotlin random


【解决方案1】:

您可以使用集合,集合是一种存在于语言中的数据结构,其中包含独特的项目

fun randomList(size: Int)List<Int> {
    val set = mutableSetOf<Int>()
    while (set.size < size) {
              set.add(/*your random here*/)
     }
     return set.toList()
}

while 使大小是所需的,并且 set 确保每次迭代中重复的数字不会被添加两次

【讨论】:

  • 谢谢,但我怎样才能使set 变量在onCreate() 中可访问?请参阅我编辑的帖子。如果我这样做,我会在set[lastIndex] 中收到错误。
  • @vasik988 set[lastIndex] 会给你错误,因为 Set 属于 Collections,所以你必须迭代它......或者你可以使用 set.toArray() 将 Set 转换为 Array ,这将返回你的数组和那么你可以使用 setArray[lastIndex].
  • toArray() 给我未解决的参考。我尝试添加import kotlin.collections但没有成功,如何引用toArray()
  • 当我设置mutableListOf 而不是mutableSetOf 时,它以我想要的方式工作。谢谢!
猜你喜欢
  • 2012-10-23
  • 2015-02-10
  • 1970-01-01
  • 2016-11-04
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
相关资源
最近更新 更多