/* Schelling’s 1970s racism model, as described in
* .
* I saw it in the article and thought I’d code it up quickly to see
* if it really behaved like the article said. It does!
* Bizarrely, though, if the racists require more than 2 neighbors to
* be the same (min_same), the clumping falls apart.
* It’s kind of awesome that you can hack together something like this in 20 minutes.
*/
#include
#include
enum { width = 64, min_same = 2 };
#define LEN(x) ((sizeof(x))/sizeof(x[0]))
int main(int argc, char **argv)
{
long generations = 512;
if (argc > 1) generations = atol(argv[1]);
if (argc > 2) srandom(atoi(argv[2]));
enum { red, blue } people[width][width];
struct { int x, y } dd[4] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
// initialize randomly
for (int ii = 0; ii < width; ii++) {
for (int jj = 0; jj < width; jj++) {
people[ii][jj] = (random() & 0x100) ? red : blue;
}
}
// each generation, swap isolated racists to random positions
for (int ii = 0; ii < generations; ii++) {
for (int jj = 0; jj < width; jj++) {
for (int kk = 0; kk < width; kk++) {
int same_neighbors = 0,
me = people[jj][kk];
for (int nn = 0; nn < LEN(dd); nn++) {
if (me ==
people[(jj + dd[nn].x + width) % width]
[(kk + dd[nn].y + width) % width]) {
same_neighbors++;
}
}
if (same_neighbors < min_same) {
int mm = random() % width,
nn = random() % width;
people[jj][kk] = people[mm][nn];
people[mm][nn] = me;
}
}
}
}
// at the end, dump out the entire system state
for (int jj = 0; jj < width; jj++) {
for (int kk = 0; kk < width; kk++) {
printf("%s", people[jj][kk] ? "--" : "##");
}
printf("\n");
}
printf("\n");
return 0;
}