Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the x value of the max y value in an array

I have an array of DataPoints, with an x and y value:

struct DataPoint: Identifiable, Hashable {
    let x: Double
    let y: Double
    
    var id: String { String(x/y) }
}

I am trying to get the x value that corresponds to the max y value. I am using this, but sometimes get an out of range error:

let dataPoints: [DataPoint] = await calculateDataPoints() 

if let index = dataPoints.indices.max(by: { dataPoints[$0].y < dataPoints[$1].y }) {
    return dataPoints[index].x
}

calculateDataPoints() is an async function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe there is another way to do this?

>Solution :

I think you should first check if the dataPoints array is empty before finding the maximum value, in my scenario if the dataPoints array is empty, the max(by:) function will return nil,so the code inside the if let block will not be executed.

If you want to return a default value of 0.0 when the dataPoints array is empty:

let dataPoints: [DataPoint] = await calculateDataPoints()

if let maxDataPoint = dataPoints.max(by: { $0.y < $1.y }) {
    return maxDataPoint.x
} else {
    return 0.0
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading