0

Is there a way to convert an Array<Int> to an Int in Kotlin? I am messing with 2D arrays and am trying to print the elements whose indexes are equal to each other. Here is my loop that tries to accomplish this:

     for (rows in arr) {
         for (elements in rows) {
-------->    if (rows == elements) {
                 print(elements)
             }
         }
         print("\n")
     }

rows is type Array<Int> and elements is type Int. I have already tried using the StringBuilder method and that does not work. Is there a function or other method that allows this? Any tips for me to do further research is appreciated.

5
  • 1
    Could your give an example of what the output should look like? Commented Mar 19, 2019 at 5:45
  • Of course. Lets say arr = [1,2] [3,4]. The output should be 1,4 since 1 is at index[0][0] and 4 is at index[3][4] Commented Mar 19, 2019 at 5:48
  • Don't you mean 4 is at [1][1]? Commented Mar 19, 2019 at 6:29
  • So is this question about finding the diagonal of a square array? Commented Mar 19, 2019 at 7:47
  • I did mean 4 is at [1][1]. The question is not about finding the diagonal of a square array. I understand that if(i < j) then all of the elements below the main diagonal would be printed out. The solution that @andras stated showed me that there is a .size function to get the entire length of the array and that was my missing piece to my problem. Commented Mar 19, 2019 at 17:07

5 Answers 5

1

Here is one way with foreach. The key is that you either iterate by indices, or you iterate by mapping the existing value with an index.

3 ways to solve this:

Any programming language styled:

    for(rowIndex in 0 until arr.size) {
        for(colIndex in 0 until arr[rowIndex].size) {
            if(colIndex == rowIndex) {
                println("[$rowIndex, $colIndex]: ${arr[rowIndex][colIndex]}")
            }
        }
    }

Python styled: (and using destructuring syntax)

    for ((rowIndex, row) in arr.withIndex()) {
        for ((colIndex, value) in row.withIndex()) {
            if(colIndex == rowIndex) {
                println("[$rowIndex, $colIndex]: $value")
            }
        }
    }

Same as previous, but using lambdas:

   arr.withIndex().forEach {
        (rowIndex, row) ->
        row.withIndex().forEach { (colIndex, value) ->
            if(colIndex == rowIndex) {
                println("[$rowIndex, $colIndex]: $value")
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I'd probably do something like this:

arr.indices.forEach { i ->
    arr[i].indices.forEach { j ->
        if (i == j) println("arr[$i][$j]==${arr[i][j]}")
    }
}

The indices extension is just one way but since you're mostly interested in them I think it's a good solution.

1 Comment

I would prefer for because of stackoverflow.com/questions/52904923/… (it doesn't seem to have changed since then).
0

If there is only one element in an array you want, and you know its index, there is absolutely no reason to iterate over the array. So I would suggest

for (i in arr.indices) {
    if (i < arr[i].size) {
        println("arr[$i][$i]==${arr[i][i]}")
    }
}

Comments

0

You can see following function

fun printDiagonalElements(){
    val row1 = intArrayOf(1,2,3)
    val row2 = intArrayOf(4,5,6)
    val row3 = intArrayOf(7,8,9)
    val row4 = intArrayOf(10,5,6,16)
    val array : Array<IntArray> = arrayOf(row1,row2,row3,row4)

    for(i in 0 .. array.size-1){
        val row = array[i]
        for (j in 0 .. row.size-1){
            if(i == j){
                println(array[i][j])
            }
        }
    }
}

Comments

0

I'm not sure why every proposed solution here iterates the elements inner array if only one its value is required.

Here is a way to print numbers in the main diagonal of a square 2D array with one loop:

arr.forEachIndexed { index, row -> 
    println("value at [$index, $index]: ${row[index]}")
}

Note however that this will throw if there are more rows than columns in this array, i.e. if the array is not square. You can add a check to ensure that there's a column with the row index in each row array:

arr.forEachIndexed { index, row -> 
    if (index in row.indices) {
        println("value at [$index, $index]: ${row[index]}")
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.