ntrix
ntrix

Reputation: 25

Second array will not increment after repeating for loop

I am new to Kotlin and am trying to compare the elements of two arrays by seeing which array has the greater element. The arrays are created via user input. The error that I am having is that when I repeat the second for loop (inner loop), which contains the contents of the second array, it will not increment to the next element of the second array unlike the first for loop. So if a = {1,2} and b = {2,1}, a would increment through both 1 and 2, but b would stay at 2 through both iterations of the loop. Here is my function that is giving me a problem:

    fun practiceCompareArray(a: Array<Int>, b: Array<Int>): Array<Int> {
        var j: Array<Int>
        var aPoints = 0
        var bPoints = 0

        for (x:Int in a) {
--------->  for (y: Int in b) {
                if (x > y) {
                    aPoints++
                } else if (x < y) {
                    bPoints++
               break
            }
        }

        j = arrayOf(aPoints, bPoints)

        return j
    }

The for loop with the arrow is giving me the problem. I think it is because of the break statement at the end of the inner loop. Do I even need the inner loop to compare each array? Any help or documentation would be helpful.

Upvotes: 0

Views: 37

Answers (1)

Harald Gliebe
Harald Gliebe

Reputation: 7564

If you know that both array have the same length and you want to compare them elementwise you could do something like:

fun practiceCompareArray(a: Array<Int>, b: Array<Int>): Array<Int> {
    var aPoints = 0
    var bPoints = 0

    for ((x,y) in a.zip(b)) {
        if (x>y) {
            aPoints ++
        } else {
            bPoints ++
        }
    }
    return arrayOf(aPoints, bPoints)
}

or in a more functional style

fun practiceCompareArray(a: Array<Int>, b: Array<Int>): Array<Int> {
    val (aPoints, bPoints) = a.zip(b)
      .fold(Pair(0,0), {(aScore, bScore), (x,y) -> 
         if (x > y) Pair(aScore + 1, bScore) else Pair(aScore, bScore + 1)})

    return arrayOf(aPoints, bPoints)
}

Upvotes: 1

Related Questions