-2
#define boyut 24

void rasgele_matris(int dizi[][boyut])
{

    srand(time(NULL)); //sistem satine göre random sayı üretecek.

    int i, j;
    for (i = 0; i < boyut; i++)
        for (j = 0; j < boyut; j++)
        { 

            int rasgele = rand() % 2;
            dizi[i][j] = rasgele;
        }
}

I want to count neighbour in my matrix. for example for dizi[2][2] indis neighbours [1][1] , [1][2] , [1][3] , [2][1] , [2][3], [3][1], [3][2], [3][3] need all neighbour indis value to sum . How to do this?

user3071284
  • 6,955
  • 6
  • 43
  • 57
FMC
  • 1

1 Answers1

0

There are a lot of posts on stack overflow regarding this problem. A good answer is here : efficient neighbours , even though the question has a java tag the code from that answer should work fine in C.

Here is an actual implementation:

#include<stdio.h>
#define MIN_X 0
#define MIN_Y 0
#define MAX_X 2
#define MAX_Y 2
int main()
{
  int sum=0;
  int grid[3][3] = {{1,1,1},{1,1,1},{1,1,1}};

  for(int i=0;i<3;i++)
    {
      for(int j=0;j<3;j++)
    {
      int thisPosX=i;
      int thisPosY=j;
      int startPosX = (thisPosX - 1 < MIN_X) ? thisPosX : thisPosX-1;
      int startPosY = (thisPosY - 1 < MIN_Y) ? thisPosY : thisPosY-1;
      int endPosX =   (thisPosX + 1 > MAX_X) ? thisPosX : thisPosX+1;
      int endPosY =   (thisPosY + 1 > MAX_Y) ? thisPosY : thisPosY+1;

      for(int rowNum=startPosX; rowNum<=endPosX; rowNum++)      
        for(int colNum=startPosY; colNum<=endPosY; colNum++)          
          sum+=grid[rowNum][colNum];    

      sum=sum-grid[i][j];
      printf("%d ",sum);
      sum=0;
    }
    putchar('\n');
    }
  return 0;
}
Community
  • 1
  • 1
Alexie Dariciuc
  • 341
  • 1
  • 3
  • 8
  • i have 24x24 matrix and does not work . i need to solve Game of life and need matrix neighbours sum. – FMC Jan 11 '16 at 19:39
  • @FatihMetehanÇelik Did you change everything accordingly ? post the code somewhere and give me the link. – Alexie Dariciuc Jan 11 '16 at 19:41
  • @FatihMetehanÇelik Don't forget MAX_X and MAX_Y must be size-1 so 23 in your case. That and the first 2 fors( change i<3 to i<24 and j<3 to j<24) are the only things you need to change. (and obviously ..the grid) – Alexie Dariciuc Jan 11 '16 at 19:50