Creating 4 digit number with no repeating elements in Kotlin

Viewed 1462

Thanks to @RedBassett for this Ressource (Kotlin problem solving): https://kotlinlang.org/docs/tutorials/koans.html

I'm aware this question exists here:

Creating a 4 digit Random Number using java with no repetition in digits

but I'm new to Kotlin and would like to explore the direct Kotlin features. So as the title suggests, I'm trying to find a Kotlin specific way to nicely solve generate a 4 digit number (after that it's easy to make it adaptable for length x) without repeating digits.

This is my current working solution and would like to make it more Kotlin. Would be very grateful for some input.

fun createFourDigitNumber(): Int {
  var fourDigitNumber  = ""
  val rangeList = {(0..9).random()}

  while(fourDigitNumber.length < 4)
  {
   val num = rangeList().toString()
    if (!fourDigitNumber.contains(num)) fourDigitNumber +=num
  }

  return fourDigitNumber.toInt()
}
1 Answers

So the range you define (0..9) is actually already a sequence of numbers. Instead of iterating and repeatedly generating a new random, you can just use a subset of that sequence. In fact, this is the accepted answer's solution to the question you linked. Here are some pointers if you want to implement it yourself to get the practice:

  • The first for loop in that solution is unnecessary in Kotlin because of the range. 0..9 does the same thing, you're on the right track there.

  • In Kotlin you can call .shuffled() directly on the range without needing to call Collections.shuffle() with an argument like they do.

  • You can avoid another loop if you create a string from the whole range and then return a substring.

If you want to look at my solution (with input from others in the comments), it is in a spoiler here:

fun getUniqueNumber(length: Int) = (0..9).shuffled().take(length).joinToString('')

(Note that this doesn't gracefully handle a length above 10, but that's up to you to figure out how to implement. It is up to you to use subList() and then toString(), or toString() and then substring(), the output should be the same.)

Related