1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Neigbour array elements

Discussion in 'C' started by ashley90, Apr 13, 2009.

  1. ashley90

    ashley90 New Member

    Joined:
    Apr 13, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I'm dealing with 2 dimensional arrays and i couldn't figure out how to do this:

    for example assume we have a 4x4 matrix, and there is a predefined number k(which is between 0 and 128).well let's declare the array as a[j]. for example if the value of a[j]>k and if the neigbors of a[j]<=k,it will count 1.
    but when a[j]>k , if one or more of a[j]'s neigbors is also bigger than k ,it will also count 1. I mean,for example if a[0][0]>k,a[0][1]>k and a[1][1]>k this whole 3 cell count as 1.

    how can i make this?
     
  2. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA
    Code:
    #include<stdio.h>
    #include<math.h>
    #define nRow 10
    #define nCol 10
    
    int main()
    {
      int mat[nRow][nCol];
      int i=0,j=0,k=34,nCount=0;
      for(i=0;i<nRow;++i)
      {
        for(j=0;j<nCol;++j)
        {
           mat[i][j] = rand()%128;
           printf("%d ",mat[i][j]);
        }
        printf("\n");
      }
    
    
      for(i=0;i<nRow;++i)
      {
        for(j=0;j<nCol;++j)
        {
          if( (i+1) < nRow && (j+1) <nCol )
          {
            if( mat[i][j]>k && ((mat[i+1][j]>=k && mat[i][j+1]>=k) || (mat[i+1][j]<k && mat[i][j+1]<k)))
             ++nCount;
          }
        }
      }
    printf("%d\n",nCount);
    
      return 0;
    }
    Try it..For any further doubts post you queries!!!
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    As I often say, try doing it yourself on paper. Write out (with the computer's help if necessary) 16 random numbers and see what the count would come to for varying values of k. This isn't a simple task and you're not going to solve it by starting to type out some code; you need to work out an algorithm first.

    Once you've done it a few times on paper you should start getting the hang of it and you can then start thinking about an algorithm for the computer to follow.

    So let's say we have
    Code:
    14 27  6 13
    15  8  4  2
     2  7 12 15
     9 23  7  1
    
    k=10
    
    the answer would be 4 (assuming the 12 and 23 aren't neighbours, so 3 if diagonal neighbours count), but how would you work that out on paper?

    Hint: if I were tasked with solving this, I'd use a second array with the same dimensions as the first.
     

Share This Page