Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* this program finds the elements in a two-dimensional array that are larger than all of their neighbors.
- So if my input is
- 3 2 9
- 13 7 6
- 1 5 8
- It should print
- 9
- 13
- 8
- */
- #include <simpio.h>
- #include "stdio.h"
- #include "genlib.h"
- #define n 3
- void initArray(int a[n][n]);
- void widenArray(int a[n][n]);
- bool neighbor(int a[n][n], int m, int p);
- main()
- {
- int a[n][n], i, j;
- initArray(a);
- widenArray(a);
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- {
- if(neighbor(a, i, j)) printf("%d", a[i][j]);
- }
- }
- getchar();
- }
- void initArray(int a[n][n])
- {
- int i, j;
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- {
- printf("a[%d][%d]= ",i,j);
- a[i][j]=GetInteger();
- }
- printf("\n");
- }
- }
- void widenArray(int a[n][n])
- {
- int i, j;
- a[n][n]=a[n+2][n+2];
- for(i=0;i<n;i++) /* This loop widens the array dimensions to n+2 and pushes the current defined values of the array to the "middle" quadrants of the array */
- {
- for(j=0;j<n;j++)
- {
- a[i+1][j+1]=a[i][j];
- }
- }
- /* The following two loops define the outland array values to -1, so we can have the same neighbor algorithm for all the middle (defined) values -- assuming the user only enters positive integers. We could define it to be, say -399, if the user wanted to enter integers from -398 on up. */
- /* verticle */
- for(i=0;i<(n+2);i++)
- {
- a[i][0]=-1;
- a[i][n+2]=-1;
- }
- /* horizontal */
- for(j=0;j<(n+2);j++)
- {
- a[0][j]=-1;
- a[n+2][j]=-1;
- }
- }
- bool neighbor(int a[n][n], int m, int p)
- {
- int i, j;
- for(i=m-1;i<=m+1;i++)
- {
- for(j=p-1;j<=p+1;j++)
- {
- if(a[i][j]>a[m][n]) return FALSE;
- }
- }
- return TRUE;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement