Search code examples
iosarraysswiftenumerate

How to get the values of two seperate Int arrays paired by index and then do conditional operation on certain pairs?


So for my first project I have been working on building a golf scorecard app. I have one array for each of a players 18 holes scores and a separate array in another class for the course par. I can get the total score subtracted from the total par to get an end result of a score 90(+18). However, if all the holes have a par set but the player only completed 9 holes the score will look like 45(-27). Players scores are 0 by default so I was thinking of trying to do

zip(playerScoreArray, courseParArray).enumerate().filter() 

where I would filter out any playerScore Holes that != 0, add those together, take the par for each of those holes and add those together, and subtract the total completed playerHoleScores from courseParNubers. This would give me an accurate + or - par only on the holes they have completed so far.

I've used the Array.reduce(0, combine +) but other than that I'm still learning the more complex ways of manipulating collections and closures.

Example of what I'm trying to accomplish:

let playerScoreArray = [7, 5, 6, 4, 0, 0, 0, 0, 0]
let holeParArray =     [4, 3, 5, 5, 4, 3, 4, 4, 4]
// get result 7-4, 5-3, 6-5, 4-5 = +5
// currentResult = 22-36 = -14

Thanks


Solution

  • You could either make that test inside reduce and only add those where the player score was non-zero:

    let total = zip(playerScoreArray, holeParArray).reduce(0) { (sum, pair) in
        return pair.0 == 0 ? sum : sum + pair.0 - pair.1
    }
    

    Or filter those pairs out before calling reduce:

    let total = zip(playerScoreArray, holeParArray).filter({ $0.0 > 0 }).reduce(0) { (sum, pair) in
        return sum + pair.0 - pair.1
    }