Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set values in 2D-array by index (Kotlin)

I define my 2D-array as followed

var row = 4
var col = 4
val myArray = Array(row) { IntArray(col) }

fun fillArray(myArray: Array<IntArray>) {
    myArray.forEach {
        it.forEach {
            var random = (1..4).random()
            myArray.set(i, random)
            Log.i(TAG, random.toString())
        }
    }
}

I have two Problems in the line

myArray.set(i, random)

First:
how can i get the current index "i" of the 2D-Array Element

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Second:
the function does not take the random generated number "random". The IDE says the type IntArray is needed.
I understand that i generated an array with int types, but i want to set a value of the type int and not IntArray so i dont quite understand what i shoul do.

If i access the value directly by index this way

numbers[0][0] = 3

everything is fine. But if i iterate over it as i showed above i cant set a value for each index.

>Solution :

Since you already know the numbers[0][0] = 3 syntax, just use that. The loops should go through the indices of myArray and the indices of each inner array.

for (outerIndex in myArray.indices) {
    for (innerIndex in myArray[outerIndex].indices) {
        myArray[outerIndex][innerIndex] = (1..4).random()
    }
}

Or if you prefer forEach:

myArray.indices.forEach { outerIndex ->
    myArray[outerIndex].indices.forEach { innerIndex ->
        myArray[outerIndex][innerIndex] = (1..4).random()
    }
}

Note that you should not forEach over the array. That goes over the elements of the array, but the original elements of the array is of no use to you, since the whole point of this is to fill the array with random values.

In fact, you could also have initialised the array with random values like this:

val myArray = Array(row) { 
    IntArray(col) { (1..4).random() } 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading