Array Hacks [Programming Tips]

If a program asks you to print the value of array elements in the same order consistently but not traversing and checking the elements every now and then, try avoiding the looping through the array every time unnecessarily. 




For example, Find the max sum of 2D Array elements in hourglass order.

Given 2D Array

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

In the above array, there are 16 hourglass order. 

int hourglassSum(int arr_rows, int arr_columns, int** arr) {
    int sum = 0, i =0, j = 0, max = 0, flag = 0;
    
    while (j <= arr_columns - HGLASS_ROW_MULTIPLIER) {
       sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] +arr[i + 1][j + 1] +
             arr[i+2][j] + arr[i+2][j + 1] + arr[i+2][j + 2];
       if (flag == 0) {
           max = sum;
           flag = 1;
       }
       max = sum > max ? sum : max;
       //printf(" %d %d %d\n  %d  \n %d %d %d\n sum %d\n",
       //    arr[i][j], arr[i][j + 1], arr[i][j + 2], arr[i + 1][j + 1],
       //     arr[i+2][j], arr[i+2][j + 1], arr[i+2][j + 2], sum);
       if (i == arr_rows - HGLASS_ROW_MULTIPLIER) {
           i = 0;
           j = j+1;
           /* To start from the row 0 but with next column */
           continue;
       }
       /* Go to the next row */
       i++; 
   }
    return max;
}

This reduces the time complexity relaitvely low.





Comments