Pedro Parreira
Pedro Parreira

Reputation: 33

compare numbers and save them in a array in Kotlin

2 part question

First part - I wanted to ask the user to give a number and then create an array with as many positions as the number introduced, how can i do this?

Second Part - The array is to be filled with random numbers but i don't want duplicate numbers . This is my code and it keeps registering duplicate numbers

var A = intArrayOf(0,0,0,0,0,0)
for (i in 0..A.size - 1) {
    val rnd = (0..10).random()
    for (j in 0..A.size-1) {
        if (rnd == A[j]){
            break
        }
        else{
            A[i] = rnd
            break
        }
    }
}

what am i doing wrong?

Upvotes: 0

Views: 261

Answers (2)

forpas
forpas

Reputation: 164089

You can ask from the user for the number of the array's items like this:

var n = 0

println("Number of items in the array = ")
try {
    n = readLine()!!.toInt()
} catch (e: Exception) {
}

Now the array will be initialized if n is a positive integer and then filled with random non repeating integer numbers:

if (n > 0) {
    val array = IntArray(n) // initialize an array of n items all being 0

    val r = Random() // create a random numbers generator
    array.indices.forEach {
        var newInt = 0
        while (array.contains(newInt)) { newInt = r.nextInt() }
        array[it] = newInt
    }
    array.forEach { print("$it ") }
}

With contains() you can check if the new generated random number already exists in the array (this means that the array will be filled with non zero integers).
If you want the random numbers to be in a specific range then instead of:

newInt = r.nextInt()

use:

newInt = r.nextInt((upperBound + 1) - lowerBound) + lowerBound

or for Kotlin version 1.3+:

newInt = (lowerBound..upperBound).random()

Upvotes: 1

Kevin Coppock
Kevin Coppock

Reputation: 134664

One thing to keep in mind is, if you're trying to generate random numbers within a range, but have no duplicates, you need to ensure that the range of random numbers is at least equal to the size of the destination array.

For instance, if you're trying to generate an array of size 12 with a range from 0..10, it can't be done as there are only 11 possibilities.

Depending on your requirements (is the range just 0 till the size of the array?) if the space of numbers is small you could simplify this quite a bit by shuffling a list from rangeStart..rangeEnd:

/**
 * Generates an array of unique random numbers between zero and the larger of
 * arraySize or upperBound. If upperBound is not specified, it defaults to be
 * arraySize.
 *
 * @param arraySize the size of the returned integer array
 * @param upperBound an optional upper bound for the range of random numbers
 */
fun generateArray(arraySize: Int, upperBound: Int = size): IntArray {
  return (0..Math.max(upperBound, arraySize)).shuffled().take(arraySize).toIntArray()
}

This also avoids wasteful generation of discarded duplicate random numbers and ensures that the function call takes a deterministic amount of time to execute.

Upvotes: 1

Related Questions