Created
August 31, 2022 10:16
-
-
Save Alexandre-cibot/dd96376a36ae03b7b4411dc2fd0e723f to your computer and use it in GitHub Desktop.
Challenge to get nb of islands present on a map.
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
// 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