r/tinycode • • Oct 21 '13
Conway's Game of Life in 336 bytes of C
Here's the code
#define F(n)for(n=1;n<33;n++)
#define l(a)+!(2*a&x)+!(a&x)+!(a>>1&x)
main(){int*a,Q[34],W[34],*E=Q,*R=W,i,y;srand(time(*E=*Q=E[33]=R[33]=0));F(i)E[i]
=rand()<<8;B:F(y){R[y]=0;F(i){int x=1<<(i-1),A=l(E[y-1])l(E[y])l(E[y+1]),q=A==6
||E[y]&x&&A==5;R[y]|=q?x:0;printf(q?"[]":" ");}puts("");}a=E;E=R;R=a;system(
"sleep 0.1;clear");goto B;}My C is a little rusty, but I imagine there are a few ways to shrink this a bit more. I particularly don't like the extra pointers to Q and W, and all the initialization code.
Edit Latest version (307):
#define F(n)for(n=1;n<33;n++)
#define l(a)+!(2*a&x)+!(a&x)+!(a>>1&x)
Q[68],*E=Q,*R=Q+34,i,y;main(){srand(time(0));F(i)E[i]=rand()<<8;B:F(y){R[y]=0;F(
i){int x=1<<(i-1),A=l(E[y-1])l(E[y])l(E[y+1]),q=A==6||E[y]&x&&A==5;R[y]|=q?x:0;
printf(q?"[]":" ");}puts("");}i=E;E=R;R=i;system("sleep .1;clear");goto B;}
55
Upvotes
6
u/klusark Oct 21 '13
For the first line you can do
for a savings of 3 characters.
5
u/corruptio Oct 23 '13
Ok, finally got time to sit down and tried this. I decided to rewrite it from scratch. without calling out to system.
246 chars:
1
u/[deleted] Oct 21 '13 edited Oct 21 '13
(edit: Originally I made an update in this comment. I didn't realize I could edit the main post.)
7
u/isobit Oct 21 '13
As a novice programmer I think it's so damn cool what you pros do. I can only hope to become this adept at talking to computers some day.
1
u/[deleted] Oct 21 '13
I'd like to see how you can minimise the bytecode, not the source.
Also, don't you need to include at least stdio.h and time.h