Skip to content

Commit f7f335c

Browse files
committed
feat: add land perimeter solution
1 parent 5141461 commit f7f335c

File tree

5 files changed

+80
-0
lines changed

5 files changed

+80
-0
lines changed

codewars/land-perimeter/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Land Perimeter
2+
3+
## Description
4+
5+
Given an array arr of strings complete the function landPerimeter by calculating the total perimeter of all the islands. Each piece of land will be marked with 'X' while the water fields are represented as 'O'. Consider each tile being a perfect 1 x 1 piece of land. Some examples for better visualization:
6+
7+
```js
8+
["XOOXO", "XOOXO", "OOOXO", "XXOXO", "OXOOO"];
9+
```
10+
11+
which represents:
12+
13+
![alt-image1](./images/image1.png)
14+
15+
should return: "Total land perimeter: 24".
16+
17+
Following input:
18+
19+
```js
20+
["XOOO", "XOXO", "XOXO", "OOXX", "OOOO"];
21+
```
22+
23+
which represents:
24+
25+
![alt-image2](./images/image2.png)
26+
27+
should return: "Total land perimeter: 18"
3.01 KB
Loading
3.12 KB
Loading

codewars/land-perimeter/solution.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const landPerimeter = (arr) => {
2+
let perimeter = 0;
3+
for (let i = 0; i < arr.length; i++) {
4+
for (let j = 0; j < arr[i].length; j++) {
5+
if (arr[i][j] === 'X') {
6+
perimeter += 4;
7+
if (i > 0 && arr[i - 1][j] === 'X') perimeter -= 2;
8+
if (j > 0 && arr[i][j - 1] === 'X') perimeter -= 2;
9+
}
10+
}
11+
}
12+
return `Total land perimeter: ${perimeter}`;
13+
};
14+
15+
module.exports = landPerimeter;
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const landPerimeter = require('./solution');
2+
3+
describe('Land Perimeter', () => {
4+
const testCases = [
5+
{
6+
input: ['OXOOOX', 'OXOXOO', 'XXOOOX', 'OXXXOO', 'OOXOOX', 'OXOOOO',
7+
'OOXOOX', 'OOXOOO', 'OXOOOO', 'OXOOXX'],
8+
output: 60,
9+
},
10+
{
11+
input: ['OXOOO', 'OOXXX', 'OXXOO', 'XOOOO', 'XOOOO', 'XXXOO', 'XOXOO',
12+
'OOOXO', 'OXOOX', 'XOOOO', 'OOOXO'],
13+
output: 52,
14+
},
15+
{
16+
input: ['XXXXXOOO', 'OOXOOOOO', 'OOOOOOXO', 'XXXOOOXO', 'OXOXXOOX'],
17+
output: 40,
18+
},
19+
{
20+
input: ['XOOOXOO', 'OXOOOOO', 'XOXOXOO', 'OXOXXOO', 'OOOOOXX', 'OOOXOXX',
21+
'XXXXOXO'],
22+
output: 54,
23+
},
24+
{
25+
input: ['OOOOXO', 'XOXOOX', 'XXOXOX', 'XOXOOO', 'OOOOOO', 'OOOXOO', 'OOXXOO'],
26+
output: 40,
27+
},
28+
];
29+
30+
it('should return a string type', () => {
31+
expect(typeof landPerimeter(testCases[0].input)).toBe('string');
32+
});
33+
34+
it.each(testCases)('should return $output as perimeter', (testCase) => {
35+
expect(landPerimeter(testCase.input))
36+
.toBe(`Total land perimeter: ${testCase.output}`);
37+
});
38+
});

0 commit comments

Comments
 (0)