(...as I learn Kotlin) I want to get the indices of the two numbers such that they add up to a specific target from a given array of integers.
Solution:
fun sum(values: Array<Int>, result: Int): Array<Int> {
for ((i, e1) in values.withIndex()) {
for ((j, e2) in values.drop(i + 1).withIndex()) { // ...or: values.drop(i + 1).forEachIndexed { j, e2 ->
//println("$i : $e1 >> $j : $e2")
if (e1 + e2 == result) {
return arrayOf(i, i + j + 1)
}
}
}
return emptyArray()
}
Test cases:
class SumTest {
@Test
fun testSum() {
Assert.assertArrayEquals(sum(arrayOf(4, 7, 9, 10, 6, 34), 10), arrayOf(0, 4))
Assert.assertArrayEquals(sum(arrayOf(5, 7, 9, 10, 21, 34), 43), arrayOf(2, 5))
Assert.assertArrayEquals(sum(arrayOf(2, 7, 11, 15), 9), arrayOf(0, 1))
Assert.assertArrayEquals(sum(arrayOf(2, 7, 8, 6, 20), 11), emptyArray())
}
}
I know this is a pretty simple algorithm, but I would like to avoid the return arrayOf(i, i + j + 1)
and modifying the values
array in the second loop (values.drop(i + 1).withIndex()
) if possible. A functional-towards approach would be great!