"Learn the process of determining the complete perimeter of various shapes through a JavaScript exercise and create a functional method

During an internship interview, I encountered a complex logical exercise that I couldn't solve. If you could provide some assistance and explain the solution to me, I would greatly appreciate it (even though I didn't pass the interview). The exercise is as follows:

"Given an array arr of strings, complete the function landPerimeter by calculating the total perimeter of all the islands. Land areas are marked with 'X' while water fields are represented as 'O'. Each tile is considered a 1 x 1 piece of land. Here are some examples for better visualization: ['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO']

View image here :

Expected result: "Total land perimeter: 24", while
['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO']

View image here:

Expected result: "Total land perimeter: 18"

I kindly request a code example demonstrating how to solve this exercise. Thank you in advance!

Answer №1

Below is a link that you may find helpful: find-perimeter-shapes-formed-1s-binary-matrix. If needed, some minor adjustments can be made based on your specific case.

<script>

function numOfNeighbour( mat,  i,  j,rows,cols) 
{ 
    var count = 0;   

    // UP 
    if (i > 0  && mat[i - 1][j]==='X') 
        count++; 

    // LEFT 
    if (j > 0  && mat[i][j - 1]==='X')         
        count++; 

    // DOWN 
    if (i < rows-1  && mat[i + 1][j]==='X')         
        count++; 

    // RIGHT 
    if (j < cols-1 && mat[i][j + 1]==='X')         
        count++; 

    return count; 
} 

function findPerimeter( mat) 
{ 
    var perimeter = 0; 
    var rows=mat.length;
    var cols=mat[0].length;

    // Traversing the matrix and finding ones to 
    // calculate their contribution. 
    for (var i = 0; i < rows; i++) 
        for (var j = 0; j < cols; j++) 
            if (mat[i][j] && mat[i][j]==='X') 
                perimeter += (4 - numOfNeighbour(mat, i ,j,rows,cols)); 

    return perimeter; 
} 

console.log("perimeter of ['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO'] is ",findPerimeter(['XOOXO', 'XOOXO', 'OOOXO', 'XXOXO', 'OXOOO'])); //24
console.log("perimeter of ['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO'] is "     ,findPerimeter(['XOOO', 'XOXO', 'XOXO', 'OOXX', 'OOOO'])); //18
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve the value of a table row by clicking with the mouse using jQuery?

I am having an issue with my table data display. Each row in the table is assigned a unique ID, which corresponds to the value of the tr-tag. My goal is to log this ID in the console when a table row is clicked. Here is the table: $.getJSON(`http://local ...

Is there a simpler method to access the source element for an event?

I'm just starting to learn JavaScript and jQuery, and right now I have the following code in my HTML: <a id="tog_table0" href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a> After that, I hav ...

In PHP, a global variable may be empty within a function, yet possess a value when accessed outside of it

I am facing an issue where the global variable does not seem to work correctly and is unable to access a specific variable. Here is a snippet of my code: function getComments($id) { global $conn; $COMPONENT_NAME = "view_company_comments"; inc ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

Is there a way to show an element on a website only when the height of the HTML content exceeds the height of the viewport?

My webpage serves as a dynamic to-do list, allowing users to add an endless number of tasks of all types. As the list grows in size, the page height increases and a scrollbar appears. Positioned at the bottom right corner of the page is a fixed button that ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

Unexpected outcomes when rigging a .dae model in Three.js with Blender

I have been working on creating a rigged model for use in a browser using Three.js. Before rigging the model, it loads perfectly fine, allowing me to move and rotate it without any issues. However, after rigging the model, the pieces load in different loca ...

The AJAX request is now being "canceled" since the website is up and running

After successfully running AJAX requests on my new version, which was in a sub directory of my site (www.staging.easyuniv.com), I moved the site to the main directory to make it live (www.easyzag.com). Although everything seems to be functioning properly, ...

Deploying and operating passport express node on azure: A comprehensive guide

I am currently developing an express node service for Single Sign-On (SSO) using the passport OAuth2 strategy. Here is the structure of my express node application code: AUTH - certs server.cert server.key -index.html -index.js (creates app as expr ...

Items plummeting below the surface plane within cannon.js and three.js

I've recently delved into the world of physics engines, specifically utilizing cannon-es.js alongside three.js. However, I've encountered a challenge where the box and loaded model are simply passing through the plane and disappearing from view. ...

Importing modules using relative paths results in failure due to module not being found, whereas employing absolute paths

I have been encountering this problem for a considerable amount of time and have made multiple attempts to resolve it. I am currently working on the development of my discord.js bot and recently switched from TS back to JS due to certain complications I fa ...

What is the best way to implement a multi-row form in Vue.js?

Form Structure: <card-wrapper v-for="(passenger, index) in form.passenger" :key="index" :icon="['fas', 'user']" :title="`Passenger ${index + 1}`" class="mb-5" > <validation-observer ...

Getting a specific index from an array using the Angular ng-repeat Directive: A step-by-step guide

I am trying to retrieve a specific index in an array using the ng-repeat directive. Currently, it is displaying information for all indexes... I only want to display the information for the second index as an example... This is my main.js: app.controll ...

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

Steps to make a dropdown menu that showcases all files within a folder using HTML5 and Javascript

I am attempting to implement a dropdown menu that displays all the files currently in a directory. The goal is for the user to be able to click on a file in the list and have the name of that file printed to the console. Here is my current progress: HTML ...

Error: React.js is unable to access the 'map' property because it is undefined

I have been facing an issue with parsing data from my Web API and displaying it on my react page. The connection is established successfully, and the data is getting parsed (verified by seeing an array of elements in the console). However, when attempting ...

Error: The program is encountering an issue because it is trying to scan a file that is not a directory in the "./src/functions/" path. This error message appears when the program encounters a "

node:internal/fs/utils:351 throw err; ^ Error: ENOTDIR: not a directory, scandir './src/functions/.DS_Store' at Object.readdirSync (node:fs:1532:3) at Object.<anonymous> (/Users/roopa/Desktop/projects/LLbot/src/bot.js:43:6 ...

Trying to update the +/- icon on an accordion dropdown, however, the local HTML file is not loading the JavaScript file. (Using Bootstrap 4)

I'm completely new to JS and struggling a bit, so please be patient. I've been searching online for a few days now without much luck. I'm using Bootstrap 4 and trying to create an accordion with a +/- icon that changes when expanded or colla ...

javascript functionality may be affected in Internet Explorer and Firefox following the upgrade to jquery version 1.8.3

After upgrading to jquery 1.8.3 from jquery 1.7 (where everything was functioning properly in all browsers), I added a javascript plugin that specifically requires jquery 1.8.2 or 1.8.3 Unfortunately, the image resizing functionality of this javascript is ...

I am looking to insert the indexes of an array into a table data cell (<td>), with the select options being the array's indexes

I'm looking for a way to add the indexes of an array as options in a select field. However, the code provided below is not working as expected. <?php $str4 = "select * from fee_names where status = '1' "; $res4 = mysql_quer ...