如何通过索引获得两个独立的Int数组的值,然后对某些对进行条件操作?

时间:2022-10-11 12:01:54

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

首先为我的项目我一直致力于建立一个高尔夫记分卡应用。我有一个数组的每个球员18洞分数和一个单独的数组在另一个类的标准。我能得到的总分中减去总面值90得到的最终结果的分数(+ 18)。然而,如果所有的洞都有一个标准值,但是玩家只完成了9个洞,那么分数将看起来像45(-27)。球员的分数默认为0,所以我想尝试这么做

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.

我要过滤掉那些!= 0的playerScore孔,把它们加在一起,把每个孔的par加到一起,然后减去所有完成的playerhol护卫舰从courseparation nubers。这只会给我一个准确的+或- par对他们已经完成的孔。

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.

我使用了数组。减少(0,合并+),但除此之外,我还在学习操作集合和闭包的更复杂的方法。

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

谢谢

1 个解决方案

#1


1  

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:

或者在调用reduce之前过滤掉这些对:

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

#1


1  

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:

或者在调用reduce之前过滤掉这些对:

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