Home > Back-end >  Creating a matrix with values in Kotlin in convenience
Creating a matrix with values in Kotlin in convenience

Time:07-07

I want to create the following one with a fancy notation:

arrayOf(intArrayOf(4, 5), intArrayOf(5, 8), intArrayOf(1, 9), intArrayOf(8, 10), intArrayOf(1, 6))

at least, cannot I achieve something that looks as follows:

arrayOf<IntArray>((4, 5), (5, 8), (1, 9), (8, 10), (1, 6))

because it is pretty awkward to rewrite intArrayOf for each row to put in.

Note that I do not ask for the following syntax I'm aware of which is used to initialize an empty matrix with values that are either same or following a common pattern.

val array = Array(row) { IntArray(column) }

CodePudding user response:

val result = listOf(4, 5, 5, 8, 1, 9, 8, 10, 1, 6)
  .chunked(2)
  .map { it.toIntArray() }
  .toTypedArray()

Edit 1:

The calculation could go into an extension function:

fun List<Int>.toArrayOfIntArrays() = this.chunked(2).map { it.toIntArray() }.toTypedArray()

val result = listOf(4, 5, 5, 8, 1, 9, 8, 10, 1, 6).toArrayOfIntArrays()

Edit 2:

Another option – assuming that the inner IntArrays all will consist of exactly two elements – would be to use a user-defined infix function:

infix fun Int.with(i1: Int) = intArrayOf(this, i1)

val result = arrayOf(4 with 5, 5 with 8, 1 with 9, 8 with 10, 1 with 6)

Any word not in conflict with the Kotlin keywords could be used, 'with' is just an example.

CodePudding user response:

If you simply don't like the wordiness of using intArrayOf you could define a shorter name to do the same, for example

fun i(vararg e: Int) = intArrayOf(*e)

And then do

arrayOf(i(4, 5), i(5, 8), i(1, 9), i(8, 10), i(1, 6))

CodePudding user response:

Here is my solution, abusing operator overloading ;)

object Matrix {
    operator fun get(vararg rows: IntArray) = rows
    operator fun get(vararg values: Int): IntArray = intArrayOf(*values)
}

fun main() {
    val result = Matrix.let { 
        it[
            it[1, 2, 3],
            it[4, 5, 6],
            it[7, 8, 9],
        ]
    }
    
    println(result.toList().map { it.toList() }) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
}

Please don't use it

  • Related