csskrouble
csskrouble

Reputation: 3

Is there a way to optimize this better?

Is there a more optimized/efficient way to do this? Tried some things, this seems right, but better to know if there is a better way of doing this. This is for my discord bot, command called "8ball" where you ask bot a question, and he replies with random reply.

            val num = Random.nextInt(1, 9)
            var text = ""
            when (num) {
                1 -> text = "Yes"
                2 -> text = "No"
                3 -> text = "Maybe yes"
                4 -> text = "Maybe no"
                5 -> text = "I don't know"
                6 -> text = "Ask csskrouble"
                7 -> text = "Ask someone else"
                8 -> text = "Rather yes"
                9 -> text = "Rather no"
            }

Upvotes: 0

Views: 75

Answers (2)

Adam Millerchip
Adam Millerchip

Reputation: 23091

You could create a Set, and ask for a random value:

setOf(
    "Yes",
    "No",
    "Maybe yes",
    "Maybe no",
    "I don't know",
    "Ask csskrouble",
    "Ask someone else",
    "Rather yes",
    "Rather no",
).random()

Upvotes: 2

AlexT
AlexT

Reputation: 2964

You could always just do:

    val text = when (Random.nextInt(1, 10)) {
        1 -> "Yes"
        2 -> "No"
        3 -> "Maybe yes"
        4 -> "Maybe no"
        5 -> "I don't know"
        6 -> "Ask csskrouble"
        7 -> "Ask someone else"
        8 -> "Rather yes"
        else -> "Rather no"
    }

Btw, in Random.nextInt(from, to), from is inclusive, but to is exclusive, meaning that you will never get a result of 9 with Random.nextInt(1, 9)

And yes, FreshD is right, you could also just do:

val text = listOf("Yes", "No", "etc").random()

Upvotes: 0

Related Questions