How to find corners in a shuffled grid?

Sometimes I face the task where I got the buffer with coordinates and I need to get the corner cells. I really confused with sorting where I need to sort values by two fields. Could you help me with the algorithm? Below I model the buffer with shuffled cells. It is known that this is a grid with four cells per row.

func howToSortThisGreed() {
    
    let xsource = [0, 1, 2, 3]
    let ysource = xsource
    let zipped = zip(xsource, ysource)
    let row = zipped.map { SIMD2<Int>([$0.0, $0.1]) }
    
    let row0 = row.map { SIMD2([0, $0.y]) }
    let row1 = row.map { SIMD2([1, $0.y]) }
    let row2 = row.map { SIMD2([2, $0.y]) }
    let row3 = row.map { SIMD2([3, $0.y]) }
    
    var buffer = row0 + row1 + row2 + row3
    buffer.shuffle()

    
    let cellPerRaw = 4
    
    
    // How to find corners of grid in the buffer?
}

This is the grid

[0.0] [1.1] [2.2] [3.3]
[1.0] [1.1] [1.2] [1.3]
[2.0] [2.1] [2.2] [2.3]
[3.0] [3.1] [3.2] [3.3]

With shuffled cells. How to get the cells [0.0], [3,3], [3,0] [3.3] from the buffer?

    guard !buffer.isEmpty else { fatalError("Empty buffer has no corners!") }
    let minX = buffer.map(\.x).min()!
    let maxX = buffer.map(\.x).max()!
    let minY = buffer.map(\.y).min()!
    let maxY = buffer.map(\.y).max()!

    let corners: [SIMD2<Int>] = [
        [minX, minY],
        [maxX, maxY],
        [maxX, minY],
        [minX, maxY],
    ]
1 Like
Terms of Service

Privacy Policy

Cookie Policy