Skip to content

Instantly share code, notes, and snippets.

@Alexandre-cibot
Created August 31, 2022 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alexandre-cibot/dd96376a36ae03b7b4411dc2fd0e723f to your computer and use it in GitHub Desktop.
Save Alexandre-cibot/dd96376a36ae03b7b4411dc2fd0e723f to your computer and use it in GitHub Desktop.
Challenge to get nb of islands present on a map.
// Land is represented as #
// water is -
// Land that connected on at least one side with another land belongs to the same island.
// Get the count of islands.
const map1 = `
------
--###-
---##-
##----
-----#
`.trim(); // 3 islands
const map2 = `
##----
--###-
---##-
##----
--#-##
`.trim(); // 5 islands
const map3 = `
------
------
------
------
------
`.trim(); // 0 islands
function getIslandsCount(map) {
const matrix = map.split("\n");
let count = 0;
const rows = matrix.map((row, i) => ({
rowIndex: i,
line: row.split("")
}));
rows.forEach(({ rowIndex, line }) => {
line.forEach((el, elIndex) => {
const beforeRowExist = rowIndex > 0;
if (el === "#" && line[elIndex - 1] !== "#") {
if (beforeRowExist) {
if (rows[rowIndex - 1].line[elIndex] !== "#") {
count++;
}
} else {
count++;
}
}
});
});
return count;
}
console.log(getIslandsCount(map3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment