Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find max/min value in array of struct

I have Dataset structure defined as

struct Dataset: Hashable {
    var x: Double
    var y: Double
}

and then array

var dataset: [Dataset]

array is filled with values and I need to find max values for both x and y struct vars. Is use of

 let maxXValue = dataset.max(by: (Dataset, Dataset) throws -> Bool)

right approach and how it should look then?

like image 284
Dawy Avatar asked Oct 28 '25 10:10

Dawy


2 Answers

You can extend Sequence and implement custom max and min methods to allow you to specify a keypath of a property that conform to Comparable:

extension Sequence {
    func max<T: Comparable>(_ predicate: (Element) -> T)  -> Element? {
        self.max(by: { predicate($0) < predicate($1) })
    }
    func min<T: Comparable>(_ predicate: (Element) -> T)  -> Element? {
        self.min(by: { predicate($0) < predicate($1) })
    }
}

let points: [CGPoint] = [.init(x: 1.2, y: 3.4),
                         .init(x: 0.1, y: 2.2),
                         .init(x: 2.3, y: 1.1)]

let maxX = points.max(\.x)
let maxY = points.max(\.y)
print("maxX:", maxX ?? "nil")
print("maxY:", maxY ?? "nil")

let minX = points.min(\.x)
let minY = points.min(\.y)
print("minX:", minX ?? "nil")
print("minY:", minY ?? "nil")

This will print

maxX: (2.3, 1.1)
maxY: (1.2, 3.4)
minX: (0.1, 2.2)
minY: (2.3, 1.1)

like image 149
Leo Dabus Avatar answered Oct 30 '25 00:10

Leo Dabus


max(by:) function will return the maximum element in the sequence, using the passed closure as the comparison between the elements.

So, you code will look like this:

let maxXValue = dataset.max { $0.x < $1.x }?.x
let maxYValue = dataset.max { $0.y < $1.y }?.y
like image 33
gcharita Avatar answered Oct 29 '25 23:10

gcharita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!