Skip to content

Instantly share code, notes, and snippets.

@ryaninhust
Created May 9, 2015 14:26
Show Gist options
  • Save ryaninhust/f405d23b519864920f52 to your computer and use it in GitHub Desktop.
Save ryaninhust/f405d23b519864920f52 to your computer and use it in GitHub Desktop.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
void print_matrix(int h, int w, int matrix[h][w]){
for(int i=1; i<h-1; i++){
for (int j =1; j<w-1; j++){
if (matrix[i][j])
printf("#");
else
printf(".");
}
printf("\n");
}
}
int count_live_neighours(int h, int w, int i, int j, int matrix[h][w]){
int count = 0;
count += matrix[i-1][j-1]
+matrix[i-1][j]
+ matrix[i-1][j+1]
+matrix[i][j+1] + matrix[i][j-1] + matrix[i+1][j-1] + matrix[i+1][j]+matrix[i+1][j+1];
return count;
}
void update_status(int h, int w, int i, int j, int matrix[h][w], int new_matrix[h][w]){
int live_count = count_live_neighours(h, w, i, j, matrix);
if (live_count==2){
new_matrix[i][j] = matrix[i][j];
}
else{
if (live_count==3){
new_matrix[i][j] = 1;
}
else
new_matrix[i][j] = 0;
}
}
void shift_update(int h, int w, int i, int j, int matrix[h][w], int new_matrix[h][w], int t){
int shift = t%2;
if (!shift)
update_status(h, w, i, j, matrix, new_matrix);
else
update_status(h,w,i,j,new_matrix, matrix);
}
int main(){
int h, w, k, n;
scanf("%d %d %d\n", &h, &w, &k);
h += 2;
w += 2;
int status_matrix[h][w];
int new_matrix[h][w];
memset( status_matrix, 0, h*w*sizeof(int) );
memset( new_matrix, 0, h*w*sizeof(int) );
char c;
for(int i=1;i<h-1;i++){
int j = 1;
while((c = getchar_unlocked()) != EOF && c != '\n')
{
if(j < w-1)
{
if (c=='.')
status_matrix[i][j] = 0;
if (c=='#')
status_matrix[i][j] = 1;
}
j++;
}
}
int shift;
#pragma omp parallel shared(status_matrix, new_matrix)
{
for (int t=0; t<k; t++){
#pragma omp for schedule(dynamic, 1)
for (int i=1; i<h-1; i++){
for (int j=1; j<w-1; j++){
shift_update(h, w, i, j, status_matrix, new_matrix,t);
}
}
}
}
if (k%2)
print_matrix(h, w, new_matrix);
else
print_matrix(h,w,status_matrix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment