Can someone help me fix my code. It is supposed to stop after 2 iterations that are the same. All it does stop after 2 iterations.
Attachments are code and pic of the input file.
Code:
#include <stdio.h>
#include <string.h>
#include <omp.h>
#include <stdlib.h>
#include <assert.h>
#define MAX_N 2000
int plate[2][(MAX_N + 2) * (MAX_N + 2)];
int which = 0;
int n;
int live(int index)
{
return (plate[which][index - n - 3] + plate[which][index - n - 2] + plate[which][index - n - 1]
+ plate[which][index - 1] + plate[which][index + 1] + plate[which][index + n + 1]
+ plate[which][index + n + 2] + plate[which][index + n + 3]);
}
int iteration() // specifying return-type as int
{
// variable change is initialized to 0, indicating there's no change in plate till now. This variable is returned at the end of the function
int change = 0;
#pragma omp parallel for schedule(static)
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
int index = i * (n + 2) + j;
int num = live(index);
int prevStatus = plate[!which][index]; //Storing the previous Status of the row and column of the plate which is to be evaluated.
if(plate[which][index])
{
plate[!which][index] = (num == 2 || num == 3) ? 1 : 0;
}
else
{
plate[!which][index] = (num == 3);
}
if(prevStatus==plate[!which][index]) // After evaluation of a particular row and column of the plate it checking if the previous Status is same as the new Status and if it is new then changing the variable change to 1, indicating the plate is changed
{
change = 1;
}
}
}
which = !which;
return change; //Return change
}
void print_plate()
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
printf("%d", plate[which][i * (n + 2) + j]);
}
printf("\n");
}
printf("\0");
}
int main()
{
double start, finish;
//start = omp_get_wtime();
int M;
char line[MAX_N];
memset(plate[0], 0, sizeof(int) * (n + 2) * (n + 2));
memset(plate[1], 0, sizeof(int) * (n + 2) * (n + 2));
if(scanf("%d %d", &n, &M) == 2)
{
for(int i = 1; i <= n; i++)
{
scanf("%s", &line);
for(int j = 0; j < n; j++)
{
plate[0][i * (n + 2) + j + 1] = line[j] - '0';
}
}
printf("Initial Configuration \n");
print_plate();
printf("\n");
int count = 0; //A new count variable is initialized with 0, indicating there's been 0 changes consecutively.
for(int i = 0; i < M; i++)
{
int change = iteration(); //Storing the return value of iteration to variable change
if(change==1) //If change is occurred then increase the count value by 1
{
count++;
}
else
{
count = 0; //If no change occurred in the plate then again reassign count to 0.
}
if(count==2) //Check if count reaches 2, if it does then add break statement to come out of loop
break;
printf("Generation: %d", i);
printf("\n");
print_plate();
printf("\n");
}
printf("Last Generation.\n");
print_plate();
//finish = omp_get_wtime();
//printf("Time: \t %f \n", finish - start);
}
return 0;
}
life_test.c