Multiplication table in Kotlin

The challenge

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

for example, when given size is 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:

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

Option 2:

package solution object Solution { fun multiplicationTable(size: Int): Array<IntArray> { return Array(size){i -> IntArray(size){(it + 1) * (i + 1)}} } }
Code language: Kotlin (kotlin)

Option 3:

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

Test cases to validate our solution

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()}") } }
Code language: Kotlin (kotlin)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments