The challenge

Create an NxN multiplication table, of size provided in parameter.

for example, when given size is 3:

1
2
3
1 2 3
2 4 6
3 6 9

for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]]

The solution in Kotlin

Option 1:

1
2
3
4
5
6
7
package solution

object Solution {
    fun multiplicationTable(size: Int) = Array<IntArray>(size) {
        i -> (1..size).map { it * (i + 1) }.toIntArray()
    }
}

Option 2:

1
2
3
4
5
6
7
package solution

object Solution {
    fun multiplicationTable(size: Int): Array<IntArray> {
        return Array(size){i -> IntArray(size){(it + 1) * (i + 1)}}
    }
}

Option 3:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package solution

object Solution {
    fun multiplicationTable(size: Int): Array<IntArray> =
        (1..size)
            .map { outer ->
                (1..size).map {
                    inner -> outer * inner
                }.toIntArray()
            }.toTypedArray()
}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package solution

import org.junit.Test
import kotlin.test.assertTrue

class ExampleTests {
     private fun Array<IntArray>.stringify(): String = "[\n" + Array(this.size,{ "  [ " + this[it].map { n -> n.toString() }.joinToString(", ") + " ]" }).joinToString("\n") + "\n]"

    @Test fun `Basic Test`() {
        val size = 3
        val user = Solution.multiplicationTable(size)
        
        val sol = arrayOf(
            intArrayOf(1,2,3),
            intArrayOf(2,4,6),
            intArrayOf(3,6,9)
        )
       
        assertTrue(user.contentDeepEquals(sol), "Expected:\n${sol.stringify()}\nGot:\n${user.stringify()}")
    }
}