How to find the maximum value in a multidimensional array with Swift

1 Answer

0 votes
import Foundation

func findMaxValue(in array: [[Double]]) -> Double {
    var maxValue = Double.leastNormalMagnitude // Initialize to the smallest possible Double value

    // Traverse the multidimensional array
    for row in array {
        for value in row {
            if value > maxValue {
                maxValue = value // Update maxValue if a larger value is found
            }
        }
    }

    return maxValue
}

// Define a multidimensional array
    let array: [[Double]] = [
        [1.0, 2.0,  3.14],
        [1.0, 1.0, 16.80],
        [3.0, 5.0, 17.50],
        [2.0, 4.0, 11.03]
    ]

// Find the maximum value
let maxValue = findMaxValue(in: array)

print("The maximum value in the array is: \(maxValue)")



/*
run:

The maximum value in the array is: 17.5

*/

 



answered Apr 6, 2025 by avibootz
...