Home > front end >  How not get out of bound in Kotlin?
How not get out of bound in Kotlin?

Time:07-16

I got the code that compare current element with the next element in array. But it crashes with out of bound because I guess when its on the last element there is no next element to compare with so it crashes.How to handle this to avoid crash and stop comparing on the last element? Here is my code

fun myFunction(arr: Array<Int>): Int{

        if (arr.isEmpty()) return 0
        var result = 0
        for (item in arr.indices) {
                if (arr[item] > 0 && arr[item   1] < 0){
                    result   
                }
                if (arr[item] < 0 && arr[item   1] > 0){
                    result   
                }
    }
        return result
    }

CodePudding user response:

The direct answer to your question:

Instead of

for (item in arr.indices)

you should write

for (item in 0..(arr.lastIndex - 1))

Explanation: arr.indices returns the range 0..arr.lastIndex but in the loop you are checking the element after the current index; therefore you should only go up to arr.lastIndex - 1.

Some further advice:

  • IntArray is more efficient than Array<Int>

  • You can combine the two if statements into one using the || (or) operator.

  • If you are counting the number of sign changes, you need to consider how to interpret 0. In your code, an input of [1,-1] would give a result of 1 sign change, but [1,0,-1] would give 0, which seems wrong. To fix that, treat 0 as positive:

if ((arr[item] >= 0 && arr[item   1] < 0) || arr[item] < 0 && arr[item   1] >= 0) {
    result  
}
  • You don't need to check if the array is empty; just remove that line. The loop won't be entered if the array is empty or if it has only 1 element.

  • Finally, you can use some cool features of the standard libray (look them up in the documentation to learn them) which can make your function succinct:

fun myFunction(arr: IntArray): Int {
    var result = 0
    arr.asList().zipWithNext().forEach { (a, b) ->
    if ((a >= 0 && b < 0) || (a < 0 && b >= 0))
        result  
    }
    return result
}

and even more succinct still:

fun myFunction(arr: IntArray) =
    arr.asList().zipWithNext().count { (a, b) -> (a >= 0) != (b >= 0) }

References: single-expression functions, zipWithNext, count, destructuring.

  • Related