12. Scanning 2D

Avoid falling off the edge, do something to each item.

Teaching Points

A process for approaching an array problem:

  1. Example: begin by writing one clear example with numbers.
  2. Skeleton: set up variables and loops (number of rows, number of columns, loop through rows, loop through columns).
  3. General case: write down code that will work most of the time (e.g., in the middle of the array).
  4. Special cases: deal with the edges of the array where things might be different.

Exercises

  1. (ddot) Suppose that nums is an NxN square array of ints. The main diagonal runs from the upper left (row=0, col=0) to the lower right (row=N-1, col=N-1). The opposite diagonal runs from the upper right (row=0, col=N-1) to the lower left (row=N-1, col=0). Find the sum of the products of the corresponding elements in the main diagonal and the opposite diagonal.

    For example: the main diagonal in the 3x3 array below is 110, 220, 330.

     110  210  310
     120  220  320
     130  230  330
    

    Running ddot on this array would give $$110\cdot 310 + 220\cdot 220+130\cdot 330.$$

  2. (wings) Given a two dimensional array, output a new array of the same size, where the item in index (row=i, col=j) of the new array is the sum of up to three items from the original array: the element at the same index (row=i, col=j), the element above that (row=i-1, col=j), and the element to the left (row=i, col=j-1).

    If there is no element of the original array at that location, then consider that element’s contribution 0.

    Discussion: what changes are needed to modify the original array instead of returning a new array (giving the same results)?

  3. (vavg) Given a two dimensional array of doubles, return an output array of the same size, but the output values are the average of numbers above and below the corresponding element in the input array. If one of those elements is not present, ignore it and use the other for the value. (In this case, you could also say the output is the average of one number from the input.)

    For example, the 4x1 input array on the left below results in the output shown on the right.

     in         vavg(in)
     100        200
     200        300
     500        400
     600        500
    
Last modified August 18, 2023: 2022-2023 End State (7352e87)