iosswift2

Finding max element in 2D array in swift


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?


Solution

  • 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()!