Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Finding land on Civilization 3 - http://nick.balestra.ch/2015/recursion-workshop/
function continentCounter (world, x, y) {
var board = world.slice();
if (board[x] === undefined || board[x][y] !== "land") {
return 0;
}
var count = 1;
board[x][y] = "counted";
// above
count = count + continentCounter(board, x-1, y-1);
count = count + continentCounter(board, x-1, y);
count = count + continentCounter(board, x-1, y+1);
// same row
count = count + continentCounter(board, x, y-1);
count = count + continentCounter(board, x, y+1);
// below
count = count + continentCounter(board, x+1, y-1);
count = count + continentCounter(board, x+1, y);
count = count + continentCounter(board, x+1, y+1);
return count;
}
var o = "water"; // water
var M = "land"; // land
var world = [
[o,o,o,o,M,o,o,o,o,o],
[o,o,o,M,M,o,o,o,o,o],
[o,o,o,o,M,o,o,M,M,o],
[o,o,M,o,M,o,o,o,M,o],
[o,o,o,o,M,M,o,o,o,o],
[o,o,o,M,M,M,M,o,o,o],
[M,M,M,M,M,M,M,M,M,M],
[o,o,M,M,o,M,M,M,o,o],
[o,M,o,o,o,M,M,o,o,o],
[M,o,o,o,M,M,o,o,o,o]
];
// Test
// continentCounter(world, 0, 4); // -> 32
// continentCounter(world, 3, 2); // -> 1
// continentCounter(world, 0, 0); // -> 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment