Skip to content

Instantly share code, notes, and snippets.

@nickbalestra
Last active September 16, 2018 23:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nickbalestra/ebe0a86271c55d99f4f2 to your computer and use it in GitHub Desktop.
Save nickbalestra/ebe0a86271c55d99f4f2 to your computer and use it in GitHub Desktop.
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