(Javascript - Arrays) Find the leftmost and rightmost connected characters

Looking for the leftmost and topmost connected '1' character in a 2D matrix?

  • Find the most left & top connected '1' character
  • Find the most right & bottom connected '1' character

EDIT 2.0:

To start, provide the coordinates for the initial '1' character.

10001
00001
11111
01110   --> (x: 1, y: 3)

The function will iterate through adjacent columns to find connected '1' characters for x or y value calculation.


Your function initiates at a specific point (e.g. y: 2, x: 0)


var array = [
 '00000',
 '01111',       --> get position of the most top & right '1'-character (x: 4, y: 1)
 '11000',
 '00000'
]

This function retrieves the top-right end of '1' characters:

var array = [
 '00000',
 '01111',      
 '11000',
 '00000'
]

Array.prototype.get_top_right = function(x_pos, y_pos) {
    var matrix = this, y1= y_pos;
    for (var x1 = x_pos; x1 < this[0].length; x1++) {
      try {
        if (matrix[(y1-1)][x1] == '1') y1--;
        else if (matrix[y1][(x1+1)] != '1') break;
      } catch(e) {}
    }; return [x1,y1]
 }
 
 var result=array.get_top_right(0,2)
 
 console.log(result)

Want to find the most bottom-left connected '1' character now?

var array = [
  '00000',
  '01111',      
  '11000', --> get position of the most bottom & left '1'-character (x: 0, y: 2)
  '00000'
]

Check out the updated function below to achieve this:

Array.prototype.get_bottom_left = function(x_pos, y_pos) {
    var matrix = this, y2= y_pos;
    for (var x2 = x_pos; x2 > 0; x2--) {
      try {
        if (matrix[(y2+1)][x2] == '1') y2++;
        if (matrix[y2][(x2-1)] != '1') break;
      } catch(e) {}
    }; return [x2,y2]
 }

Don't forget to test your updated function with the error_array provided below.

var error_array = [
    '000000',
    '000011',
    '111110',
    '111111'
] 

If you encounter any issues, seek help from the community. Good luck!

Best regards,
- hans

Answer №1

Two variations of the get_bottom_left function were created:

  • bottom_left_up which moves from the point (x, y) to the left and up
  • bottom_left_down that moves from the point (x, y) to the right and down.

Implementation details are as follows:

Array.prototype.bottom_left_up = function(x, y) {
  if(this[y][x] === '0') {
    return;
  }
  while(y >= 0) {
    while(--x >= 0) {
      if(this[y][x] === '0') {
        return [x + 1, y];
      }
    }
    if(--y === -1 || this[y][this[y].length - 1] === '0') {
      return [0, y + 1];
    }
    x = this[y].length;
  }
};

Array.prototype.bottom_left_down = function(x, y) {
  if(this[y][x] === '0') {
    return;
  }
  while(y < this.length) {
    if(this[y].indexOf('0', x) !== -1) {
      return [x, y];
    }
    if(++y === this.length || this[y][0] === '0') {
      return [x, y - 1];
    }
    x = 0;
  }
};

No out-of-range protections are present in the code, but they can be easily added without any issues. Let's validate the logic with some tests:

var array = [
 '00000',
 '01111',
 '11000',
 '00000'
];
console.log(array.bottom_left_up(2, 1)); // [1, 1]
console.log(array.bottom_left_down(2, 1)); // [0, 2]

var array2 = [
  '000000',
  '000011',
  '111110',
  '111111'
];
console.log(array2.bottom_left_up(3, 3)); // [0, 3]
console.log(array2.bottom_left_down(3, 3)); // [3, 3]

When it comes to method protection, using try-catch is not recommended. Instead, consider a solution like the following:

function(x, y) {
  x = parseInt(x, 10);
  y = parseInt(y, 10);
  if(!this.length || isNaN(x) || isNaN(y) || x < 0 || y < 0 || x >= this.length || y >= this[0].length) {
    return;
  }
  // ...
}

This way, 'undefined' will be returned in cases of an empty array, incorrect parameters, or no match found.

Answer №2

Check out this function that can handle matrices of any size, although I'm unsure if you always want to locate the first occurrence of "1" in the matrix, even if it's isolated on a line and to the right side.

    var array = [
    '00000',
    '01111',       
    '11000',
    '00100'];

var error_array = [
    '000000',
    '000011',
    '111111',
    '111111',
    '000000',
    '000010',
    '100000'
    ] 


getLeftBottom(error_array);

function getLeftBottom(testArray)
{
    var firstFound;
    for (var index = testArray.length; index > 0; index--)
    {
        console.log(testArray[index-1]);
        str = testArray[index-1];
        firstFound = str.indexOf("1");
        if (firstFound !== -1)
        {
            console.log("Coordinates: x = {0}, y = {1}", firstFound, index)   // This part behaves differently than expected in JavaScript, but still useful for locating the coordinates
            break;
        }

    }
}

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

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

Issue with setting background image height to 100% or 100vh

Seeking help to address the issue of the URL field impacting the total height. Any assistance would be greatly appreciated. body,html { height:100% } Issue arises when there is a display in the address bar. .bg { min-height:100% background-size: cover; ...

jquery dialog box displaying a webpage

I am looking to implement a feature where, upon clicking the edit link in the last column of my dataTable, a separate page for editing should open within a jQuery dialog box. The goal is to seamlessly submit data while providing a user-friendly experienc ...

Challenges Encountered When Inputting Year in ReactJS Date Picker Component

I've encountered a problem with a date input component in my ReactJS project and need some assistance with resolving two issues: Problem 1: Year Input Length The first issue is that the year input field allows six digits, but I want to restrict it to ...

Understanding how jQuery ready function works is essential in ensuring proper

My question is regarding an object I have created: function myObj (){ this.name = "noName"; } myObj.prototype = { init: function(){ console.log(this); this.setName(); }, setName: function(){ this.name = "object name"; } } var ob ...

Sending a POST Request between two websites using JavaScript

I am facing an issue where I need to send a POST request from an application on SERVER1 to another application running on SERVER2. SERVER1: <form name="submitForm" method="POST" action="http://SERVER2:4120/download_item/&qu ...

Trigger a random tune when hovering the mouse

I need help figuring out how to make a fixed image on my page trigger a random sound track when hovered over. The sound could be one of five different tracks. Here is the HTML for my image: <img src="images/Airplane.png" class="Airplane-photo"> Bel ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

Creating a table from a PHP associative array

I've been attempting to organize an associative array in ascending order and then display it in an HTML table, but I've hit a roadblock with an error. I tried searching for solutions here on SO and followed the advice provided in some threads: P ...

Learn how to configure and utilize an AngularJS factory using ngResource along with passing parameters in the call

As a newcomer to Angular, I'm seeking guidance on creating a new factory utilizing ngResource instead of $http, with the ability to pass parameters. Following an example provided here, I have defined my factory as shown below: app.factory('abst ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...

The array within the document is unable to perform $push, $pull, and $inc operations simultaneously

In my collection, each document follows this format: { "_id": "57e81e0d5891000c99cc133b", "name": "service_name", "use": 8, "errors": [], } The errors field may contain objects like: { "e": { "error": "socket hang up" }, "d": "2016-10- ...

Issue with ExtJS causing store to not load properly

I have been working on this issue for over a week now and cannot seem to get it resolved. The webservice is returning data, which I can see, but the store is not loading it correctly. The only time I managed to display the entire response in the grid was w ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Incorporating external JavaScript into a Rails application

Having trouble with the syntax on this simple problem. Struggling to find examples of externally linked files, all solutions online involve storing a local copy instead. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" typ ...

Error: Unexpected identifier in jQuery ajax line

I'm currently encountering an issue with my jQuery ajax call that's throwing an "Uncaught SyntaxError: Unexpected identifier" error at line 3. For confidentiality reasons, I have omitted the original URL. However, even after removing the csrHost ...

Developing a dynamic table using HTML and JavaScript

I have a question that might sound silly, but I am trying to retrieve the HTML content from this particular website using JavaScript. The data I'm interested in is located at the center of the page within a dynamic table which does not change the URL ...

Successive promises of catches

Here is a situation that I am dealing with: controller.ts methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } service.ts someMethod(): ng: ...