Invert values in Kotlin

0 min read 111 words

The challenge

Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []

The solution in Kotlin code

Option 1:

fun invert(arr: IntArray) = arr.map { -it }.toIntArray()

Option 2:

fun invert(arr: IntArray): IntArray {
    return IntArray(arr.size){ -arr[it] }
}

Option 3:

fun invert(arr: IntArray): IntArray {
    var x = 0
    while (x < arr.size) {
        arr[x] = arr[x] * -1
        x++
    }
    return arr
}

Test cases to validate our solution

import org.junit.Assert.*;
import org.junit.Test

class TestExample {
  @Test
  fun testFixed() {
    assertArrayEquals(intArrayOf(-1,-2,-3,-4,-5), invert(intArrayOf(1,2,3,4,5)))
    assertArrayEquals(intArrayOf(-1,2,-3,4,-5), invert(intArrayOf(1,-2,3,-4,5)))
    assertArrayEquals(intArrayOf(), invert(intArrayOf()))
    assertArrayEquals(intArrayOf(0), invert(intArrayOf(0)))
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts