Last active
December 6, 2017 20:53
-
-
Save idiomatic/70a285403501a17238c968f9eda65428 to your computer and use it in GitHub Desktop.
count the number of "islands" in an matrix of non-wraparound bits, where horizontally/vertically/diagonally adjacent bits are the same island
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tests = [ | |
[0, [[0]]], | |
[1, [[1]]], | |
[1, [[1, 0], [0, 0]]], | |
[1, [[0, 1], [0, 0]]], | |
[1, [[0, 0], [1, 0]]], | |
[1, [[0, 0], [0, 1]]], | |
[1, [[1, 0], [0, 1]]], | |
[1, [[0, 1], [0, 1]]], | |
[1, [[1, 0], [1, 0]]], | |
[1, [[0, 1], [1, 0]]], | |
[1, [[1, 1], [1, 1]]], | |
[2, [[0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]]], | |
[16, [[0, 1, 0, 1, 0, 1, 0, 1], | |
[0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 1, 0, 1, 0, 1, 0, 1], | |
[0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 1, 0, 1, 0, 1, 0, 1], | |
[0, 0, 0, 0, 0, 0, 0, 0], | |
[0, 1, 0, 1, 0, 1, 0, 1], | |
[0, 0, 0, 0, 0, 0, 0, 0]]] | |
].forEach( | |
([expected, map], i) => | |
console.assert(countIslands(map) == expected, `test ${i} failed`) | |
) | |
function countIslands(map) { | |
const height = map.length | |
const width = map[0].length | |
var islands = 0 | |
for (let y = 0; y < height; y++) { | |
for (let x = 0; x < width; x++) { | |
if (map[y][x]) { | |
if (!(map[y][x-1] | |
|| ((y > 0) && | |
(map[y-1][x-1] || map[y-1][x] || map[y-1][x+1])))) { | |
islands++ | |
} | |
} | |
} | |
} | |
return islands | |
} | |
exports = { countIslands } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment