Kotlin - 不重复的随机数

Cer*_*ber 7 sorting random kotlin

我有一个问题,如何防止随机数重复。顺便问一下,有人可以向我解释如何对这些随机数进行排序吗?

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val textView = findViewById<TextView>(R.id.textView)
    val button = findViewById<Button>(R.id.buttom)


    button.setOnClickListener {

        var liczba = List(6){Random.nextInt(1,69)}
        textView.text = liczba.toString()
    }
}
Run Code Online (Sandbox Code Playgroud)

aSe*_*emy 9

序列是生成数据流并限制或过滤结果的好方法。

import kotlin.random.Random
import kotlin.random.nextInt

val randomInts = generateSequence {
  // this lambda is the source of the sequence's values
  Random.nextInt(1..69)
}
  // make the values distinct, so there's no repeated ints
  .distinct()
  // only fetch 6 values
  // Note: It's very important that the source lambda can provide
  //       this many distinct values! If not, the stream will
  //       hang, endlessly waiting for more unique values.
  .take(6)
  // sort the values
  .sorted()
  // and collect them into a Set
  .toSet()
Run Code Online (Sandbox Code Playgroud)

在 Kotlin 游乐场中运行

为了确保其有效,这里有一个使用Kotest 的基于属性的测试。

import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeMonotonicallyIncreasing
import io.kotest.matchers.collections.shouldBeUnique
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.property.Arb
import io.kotest.property.arbitrary.positiveInts
import io.kotest.property.checkAll
import kotlin.random.Random
import kotlin.random.nextInt


class RandomImageLogicTest : FunSpec({

  test("expect sequence of random ints is distinct, sorted, and the correct size") {
    checkAll(Arb.positiveInts(30)) { limit ->

      val randomInts = generateSequence { Random.nextInt(1..69) }
        .distinct()
        .take(limit)
        .sorted()
        .toSet()

      randomInts.shouldBeMonotonicallyIncreasing()
      randomInts.shouldBeUnique()
      randomInts.shouldHaveSize(limit)
    }
  }

})
Run Code Online (Sandbox Code Playgroud)

测试通过!

Test                                      Duration  Result
expect sequence of random ints is di...   0.163s    passed
Run Code Online (Sandbox Code Playgroud)


ros*_*sum 8

可以使用三种基本方法来避免重复“随机”数字。如果它们不重复,那么它们当然不是真正随机的。

  • 对于范围较小的数字,将数字随机洗牌,洗牌后按顺序挑选。

  • 对于中等大小的号码,记录您选择的号码,并拒绝任何重复。如果您选择大部分可用数字,这会变得很慢。

  • 对于非常大范围的数字,您需要类似加密的东西:将 0、1、2、3 ... 映射到(大)范围内的数字的一对一映射。例如,128 位加密将给出非重复 128 位数字的明显随机排序。