How to find the greatest product of 3 adjacent numbers in the same (any) direction in a grid with Swift

1 Answer

0 votes
import Foundation

func findGreatestProduct(_ grid: [[Int]]) -> (Int, Int, Int, Int) {
    let rows = grid.count
    let cols = grid[0].count
    var maxProduct = 0
    var maxnumber1 = 0, maxnumber2 = 0, maxnumber3 = 0

    for i in 0..<rows {
        for j in 0..<cols {
            // Horizontal (right)
            if j + 2 < cols {
                let product = grid[i][j] * grid[i][j + 1] * grid[i][j + 2]
                if product > maxProduct {
                    maxProduct = product
                    (maxnumber1, maxnumber2, maxnumber3) = (grid[i][j], grid[i][j + 1], grid[i][j + 2])
                }
            }

            // Vertical (down)
            if i + 2 < rows {
                let product = grid[i][j] * grid[i + 1][j] * grid[i + 2][j]
                if product > maxProduct {
                    maxProduct = product
                    (maxnumber1, maxnumber2, maxnumber3) = (grid[i][j], grid[i + 1][j], grid[i + 2][j])
                }
            }

            // Diagonal (down-right)
            if i + 2 < rows && j + 2 < cols {
                let product = grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2]
                if product > maxProduct {
                    maxProduct = product
                    (maxnumber1, maxnumber2, maxnumber3) = (grid[i][j], grid[i + 1][j + 1], grid[i + 2][j + 2])
                }
            }

            // Diagonal (down-left)
            if i + 2 < rows && j >= 2 {
                let product = grid[i][j] * grid[i + 1][j - 1] * grid[i + 2][j - 2]
                if product > maxProduct {
                    maxProduct = product
                    (maxnumber1, maxnumber2, maxnumber3) = (grid[i][j], grid[i + 1][j - 1], grid[i + 2][j - 2])
                }
            }
        }
    }

    print("maxnumber1: \(maxnumber1)")
    print("maxnumber2: \(maxnumber2)")
    print("maxnumber3: \(maxnumber3)")

    return (maxProduct, maxnumber1, maxnumber2, maxnumber3)
}

func main() {
    let grid = [
        [1, 2, 3, 4, 5, 6, 7],
        [8, 9, 10, 11, 12, 13, 14],
        [49, 49, 99, 40, 17, 81, 18],
        [44, 20, 45, 35, 14, 0, 61],
        [26, 97, 17, 78, 80, 96, 83],
        [16, 7, 97, 57, 32, 16, 27],
        [60, 74, 31, 49, 71, 48, 86]
    ]

    let (result, _, _, _) = findGreatestProduct(grid)

    print("Greatest product of 3 adjacent numbers: \(result)")
}

main()



/*
run:

maxnumber1: 80
maxnumber2: 96
maxnumber3: 83
Greatest product of 3 adjacent numbers: 637440

*/

 



answered Jul 26, 2025 by avibootz
...