/* This applet demonstrates a paper by Thomas Schelling called _Dynamic Models of Segregation_. Each cell in the grid has eight neighbors. The threshold is the number of "different" neighbors a cell will accept. The density is how many "empty" cells are available to move to. */ float threshold = .65; // Threshold for "diversity" between 0 and 1 float density = 0.95; // How dense is the grid (0 to 1). int hoodRadius = 3; // How large is a cell's neighborhood /* Display variables */ int cellSize = 2; int cellsX = 200; int cellsY = 200; /* The world */ int[][] grid = new int[cellsX][cellsY]; /* Our groups */ color empty = #FFFFFF; color poor = #EE22EE; color rich = #22EE22; /* Click to start */ void setup() { background(empty); noStroke(); size(cellsX*cellSize, cellsY*cellSize,P2D); seedGrid(); colorGrid(); } void draw() { shuffle(); colorGrid(); } void mousePressed() { setup(); noLoop(); } void keyPressed() { loop(); } void seedGrid() { for(int x = 0; x < cellsX; x++) { for(int y = 0; y < cellsY; y++) { float densityChance = random(1.0); if (density < densityChance) { grid[x][y] = -1; } else { grid[x][y] = (int)random(-1,2); } } } } void colorGrid() { for(int x = 0; x < cellsX; x++) { for(int y = 0; y < cellsY; y++) { switch(grid[x][y]) { case -1: fill(empty); break; case 0: fill(poor); break; default: fill(rich); break; } //ellipse(x*cellSize,y*cellSize,cellSize,cellSize); rect(x*cellSize,y*cellSize,cellSize,cellSize); } } } void shuffle() { for(int i = 0; i < cellsX*cellsY/2; i++) { int x = (int)random(cellsX); int y = (int)random(cellsY); int others = numDifferent(x,y); if(others/(8.0*hoodRadius) >= threshold) { move(x,y); } } } int numDifferent(int x, int y) { int different = 0; if(grid[x][y] == -1) { return 0; } else { for(int i = x-hoodRadius; i <= x+hoodRadius; i++) { for(int j = y-hoodRadius; j <= y+hoodRadius; j++) { if(grid[x][y] != grid[(i+cellsX)%cellsX][(j+cellsY)%cellsY]) { if(grid[(i+cellsX)%cellsX][(j+cellsY)%cellsY] != -1) { different++; } } } } return different; } } void move(int x, int y) { int moved = 0; int newX = 0; int newY = 0; while(moved == 0) { newX = (int)random(cellsX); newY = (int)random(cellsY); if(grid[newX][newY] == -1) { moved++; } } grid[newX][newY] = grid[x][y]; grid[x][y] = -1; }