I am complete novice who is trying to supplement online course learning, by building some rudimentary programs. I am currently trying to build a program to calculate one's golf index. In order to do this, I must first calculate the average of the lowest 8 rounds, of the golfer's last 20. Calculating the average of the last 20 rounds was easy enough. It is isolating the lowest 8 rounds from the last twenty that I cannot figure out.
Generalized, how does one calculate the sum of the lowest N values in an array?
A note for the golfers out there: for the purposes of this exercise I am imagining that the individual only plays at one course, with a par of 72. I realize that the program will not work as currently constructed if par changes.
var scores: Array = [98, 99, 87, 86, 88, 92, 88, 87, 84, 98, 85, 84, 80, 99, 100, 101, 94, 96, 79, 99, 92, 94, 87, 99, 80]
var lastTwentyScores = scores.suffix(20)
var total = lastTwentyScores.reduce(0, )
var avg = Double(total) / Double(lastTwentyScores.count)
var index = avg - 72
Right now, it is giving me the average of the last twenty - 72.
I know I will need to create a new variable, and change the final divisor to 8, instead of 20. I just don't know how to call the 8 lowest values from the array.
CodePudding user response:
Like @HangarRash said, it's a lot easier to do this if you sort the scores first. Simply sort the array in ascending order, and fetch the first 8 elements.
var scores: Array = [98, 99, 87, 86, 88, 92, 88, 87, 84, 98, 85, 84, 80, 99, 100, 101, 94, 96, 79, 99, 92, 94, 87, 99, 80]
scores = scores.sorted() //Sorts the scores (from least to greatest)
var eightLowestScores: Array = scores[...8] // Gets the first 8 elements based on their index.
CodePudding user response:
You just need to sort the last 20 and take the first 8 of that sorted result. That will give you the lowest 8 of the last 20.
var scores: Array = [98, 99, 87, 86, 88, 92, 88, 87, 84, 98, 85, 84, 80, 99, 100, 101, 94, 96, 79, 99, 92, 94, 87, 99, 80]
var lastTwentyScores = scores.suffix(20)
var lowestEightScores = lastTwentyScores.sorted().prefix(8)
var total = lowestEightScores.reduce(0, )
var avg = Double(total) / Double(lowestEightScores.count)
This gives a total of 666 and an average of 63.25.
You can simplify most of the code to just:
var total = scores.suffix(20).sorted().prefix(8).reduce(0, )
This makes it nice and neat but having the intermediate steps can make it easier to read and certainly easier to debug.
CodePudding user response:
I think you are looking for this:
scores
.suffix(20) // last 20
.sorted() // sort to get the ordered slice
.prefix(8) // 8 lowest
.reduce(0, ) / 8 // average