As we have support for Array to find max element using maxElement(), do we have any method using which we find max element in a 2D array Array<Array<Double>> in swift-2.0? Or do we need to write our own method?
4 Answers
I don't know of any built in support for that but I suppose this is a simple enough solution
var matrix = [[3,5,4,6,7,],[9,2,6,8,3,5],[1,2,6,7,8,4]]
let max = matrix.maxElement({ (a, b) -> Bool in
return a.maxElement() < b.maxElement()
})?.maxElement()
max is Optional(9) in this case
or you can use map for the same
let max2 = matrix.map({ (a) -> Int in
return a.maxElement()!
}).maxElement()!
shorter version
let max3 = matrix.map({ $0.maxElement()!}).maxElement()!
1 Comment
Gargo
In the first case you call
maxElement unpredicatable count of times and each time it iterates through all the array items. In the second and third case you iterate through all items twice wasting cpu resources and memory (because you don't apply any filters).The most optimized and universal solution:
struct CustomObject {
var date: Date
}
let objectComparator = { (p1: CustomObject, p2: CustomObject) in
p1.date > p2.date
}
let result = params.compactMap {
$0.max(by: objectComparator)
}
.max(by: objectComparator)
After compactMap you get a flatten array which consists of max elements from the nested arrays. Then you apply max for the second time.
This code uses as little memory and cpu as possible.
maxElement()for each "row" and then usemaxElementon that