File:Backtang2.png
Summary
| Description |
Italiano: Bak–Tang–Wiesenfeld sandpile, 28 million grains |
| Date | |
| Source | Own work |
| Author | Claudio Rocchini |
Licensing
I, the copyright holder of this work, hereby publish it under the following license:
This file is licensed under the Creative Commons Attribution 3.0 Unported license.
- You are free:
- to share – to copy, distribute and transmit the work
- to remix – to adapt the work
- Under the following conditions:
- attribution – You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
Source Code
#include <stdio.h>
#include <stdlib.h>
#include <queue>
typedef unsigned char byte;
typedef std::pair<int,int> coord;
const int N = 1024;
const size_t C = 4;
const size_t S = 28000000;
byte M[N][N];
const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
int main() {
memset(M,0,N*N);
for(size_t steps=0;steps<S;++steps) {
std::queue<coord> q;
if( ++M[N/2][N/2]>=C ) q.push( coord(N/2,N/2) );
while( !q.empty() ) {
const int x = q.front().first;
const int y = q.front().second;
q.pop();
if(M[x][y]<C) continue;
M[x][y] -= 4;
for(int d=0;d<4;++d) {
const int lx = x+dx[d];
const int ly = y+dy[d];
if(lx<0 || lx>=N) continue;
if(ly<0 || ly>=N) continue;
if(++M[lx][ly]>=C) q.push( coord(lx,ly) );
}
}
}
const byte co[4][3] = { {255,255,255}, {255,0,0}, {0,255,0}, {0,0,255} };
FILE * fo = fopen("backtang2.ppm","wb");
fprintf(fo,"P6\n%d %d\n255\n",N,N);
for(int x=0;x<N;++x) for(int y=0;y<N;++y)
fwrite(co[M[x][y]],1,3,fo);
fclose(fo);
return 0;
}