Reputation: 149
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?
Upvotes: 1
Views: 2296
Reputation: 351
You can use flatMap to convert to a 1D array, then take the max of that...
let max = matrix.flatMap { $0 }.max()
max is Optional(9)
Upvotes: 0
Reputation: 1380
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.
Upvotes: 0
Reputation: 467
import UIKit
var val= [
[2, 4, 9],
[3, 6, 0],
[8, 7]
]
func raiseLowerValue(inout val: [[Int]]) {
for row in 0..<image.count {
for col in 0..<image[row].count {
if image[row][col] < 5 {
image[row][col] = 5
}
}
}
}
by substituting "if" you can use by sort! or the other way.
Upvotes: 0
Reputation: 7906
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()!
Upvotes: 0