Capstone: Transpose and Combined Algorithms

Part of: 2D Array

Bringing It Together. The transpose of a grid swaps its rows and columns: the cell at (r, c) in the original moves to (c, r) in the result. A grid with R rows and C columns transposes into one with C rows and R columns. Transposition is the ultimate rows vs. columns exercise because it forces you to track both index orders at once. Sizing the Result Correctly. - The result has dimensions [numCols][numRows], new int[grid[0].length][grid.length]. - The assignment is t[c][r] = grid[r][c]; swapping the indices is the whole trick. Combining Standard Algorithms. Real problems chain the patterns from this unit: - Traverse in row-major order to read the grid. - Use per-row or per-column accumulators for statistics. - Apply search-and-position to locate values. - Restructure with a transpose when the orientation must change. What usually goes wrong. What you see What caused it How to fix it --- --- --- ArrayIndexOutOfBoundsException while filling the result The result was sized [numRows][numCols] instead of the other way round Size it new int[grid[0].length][grid.length] The output looks identical to the input The write was t[r][c] = grid[r][c], which copies without swapping anything The wr

Challenge: Transpose the Grid