Identify available space within a two-dimensional array

For the angular gridster, I need to determine the dimensions of a new element being added when there is no space for the current element. Let's simplify this by considering a 2-dimensional array with values true or false. My goal is to search for the first available space in the array to find the position (x, y) and the width and height of that free space. Here is what I have so far:

var matrix = [
  [false, false, false, false, false, false],
  [false, false, false, false, false, false],
  [false, false, false, false, false, false],
  [false, false, false, true, true, true],
  [false, false, false, true, true, true]
];
var place = {};
loop:
for (var i=0; i<matrix.length; i++) {
  for (var j=0; j<matrix[i].length; j++) {
    if (matrix[i][j] && !place.x && !place.y) {
      place.x = j;
      place.y = i;
      place.width = 0;
      place.height = 0;
      for (var y=i; y<matrix.length; y++) {
        for (var x=j; x<matrix[y].length; x++) {
          if (matrix[y][x]) {
            place.width =  x - j + 1;
            place.height = y - i + 1;
          }
        }
      }
      break loop;
    }
  }
}
console.log(place);

However, this approach fails for arrays like:

var matrix = [
  [false, false, false, false, false],
  [false, false, false, false, false],
  [false, false, false, false, false],
  [true, true, false, true, true],
  [true, true, false, true, true]
];

I am seeking guidance on how to adjust my code to work for arrays like the one above. The expected result should be:

{x:0, y:3, width: 2, height: 2}

Answer №1

Here's an alternative approach I took to tackle the issue by breaking it down into smaller parts:

  1. Determine the first true element in the matrix
  2. Calculate the number of adjacent true elements starting from that point

For more details, you can refer to this fiddle link and review the provided code snippet. Hopefully, this solution proves helpful.

function findCoords(matrix) {
  for (var row = 0; row < matrix.length; row++) {
    for (var col = 0; col < matrix[row].length; col++) {
      if (matrix[row][col]) {
        return createCoordsObj(row, col, matrix);
      }
    }
  }
  return null;
}

function createCoordsObj(row, col, matrix) {
  return {
    x: col,
    y: row,
    width: find('width', row, col, matrix),
    height: find('height', row, col, matrix)
  };
}

function find(type, row, col, matrix) {
  var res = 0;
  while (matrix[row] && matrix[row][col]) { // will finish when element in matrix is false || undefined
    res += 1;
    col += type === 'width' ? 1 : 0;
    row += type === 'width' ? 0 : 1;
  }
  return res;
}

console.log(findCoords([
  [false, false, false, false, false],
  [false, false, false, false, false],
  [false, false, false, false, false],
  [true, true, false, true, true],
  [true, true, false, true, true]
]));

Answer №2

If you are looking for a solution, you can try the following method; It will provide you with the coordinates of the top left corner, as well as the dimensions of an empty space. In case there is no empty space (all false), the function will return a value of false.

var matrix = [
  [false, false, true, true, true],
  [true, true, true, true, true],
  [true, true, false, false, false],
  [true, true, false, false, false],
  [true, true, false, false, false]
],
 emptySpaceCoordinates = (arr) => { var x,
                        y = arr.findIndex(row => (x = row.findIndex(col => col), x !== -1));
                        w = 0,
                        h = 0;
                    while (arr[y] && arr[y][x+w]) w++;
                    while (arr[y+h] && arr[y+h][x]) h++;
                    return !!~y && {x:x,y:y,width:w,height:h};
                  };
console.log(emptySpaceCoordinates(matrix));

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

Why do the values of rows and columns suddenly turn into unforeseen numbers once I modify the input assigned to them?

Greetings! I have been working on a simulation of a forest fire spreading, and I am almost done with it. However, I encountered an issue when I tried switching the numbers of rows and columns - suddenly they became huge numbers for no apparent reason. I kn ...

Bootstrap Toggle Button with Dropdown Menu

I have a button-group with font awesome icons and a dropdown on one of them, as illustrated in the example below. I am trying to toggle the button status, but for some reason, the 'active' class is automatically removed on mouseout. It seems to ...

Implementing restify on a website that mandates user login authentication

Currently, I am operating a REST API server using restify. In addition, my front-end consists of angularjs with html, css, and js files hosted on an Apache webserver. The next step is to implement user login authentication for this webapp. Access to the w ...

Is there a way to retrieve the current date and time from the server using AngularJS?

My AngularJs project is experiencing issues with the local system time and date being incorrect. I am in search of a solution to retrieve the server time and date instead. Can anyone guide me on how to achieve this? ...

Ways to stop user authentication in Firebase/Vue.js PRIOR to email verification

I am currently working on a Vue.js and Firebase authentication interface with an email verification feature. The setup is such that the user cannot log in until they click the verification link sent to the email address provided during the login process. ...

Troubleshooting the issue of autoplay not functioning in HTML5 audio

I'm facing a strange issue with my code - the autoplay feature for audio is not working as expected. Typically, whenever I insert this particular piece of code into a website, the music starts playing automatically. However, it seems to be malfunctio ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

ng-bind stops updating after entering text into input field

I am a newcomer to AngularJS and I have encountered an issue that I am struggling to resolve. Although I found a similar question on stackoverflow, the solution provided did not work for me. The problem I am facing is that when I input text into any of the ...

How can one easily implement a countdown timer in an Ionic 3 app?

Easily create an Ionic3 timer set to 2 minutes that displays countdown like 1:59, 1:58, and finally reaches 00:00. Once the timer hits 00:00, a block of HTML content will be shown. ...

What can you tell me about creating a dropdown tree combo box using JavaScript?

Upon reviewing my work, I noticed that the sequence of the drop-down boxes has been inadvertently reversed. This is not aligned with the desired outcome. How can I utilize a method to ensure that the order of the drop-down boxes is correct? However, this ...

Ways to address the Uncaught TypeError: Cannot read property 'field' Tabulator error

My Current Task: I have Tabulator table data serialized and saved in my database. At this point in my script, I am retrieving and parsing the data. My goal is to organize the column data into an array to populate my Tabulator table, taking into account col ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Incorporating the Intro.JS library into a Vue-Cli/Webpack project

For my first project utilizing vue-cli and webpack, I am facing a challenge in integrating an external JavaScript library. The library in question is Intro.js, which only requires me to import intro.js, add specific tags to HTML elements, and execute the ...

Is there a way to send an Ajax response to the web browser client as a downloadable file?

In my MVC 3 project, I have generated a csv file in an Action Method on the server named GetCSV() which is designated as an [HttpPost] action method. My goal is to send this csv file directly to the web browser for download. While I was able to achieve t ...

Create a new function that generates a unique div element

How can I replicate this function in a different container? function goto(id, t){ // Move to the designated div id using animation $(".headbox-wrapper").animate({"left": -($(id).position().left)}, 600); // Remove the "active" class from a ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...

Creating original random integers within the range of 0 to 'x'

I'm looking to create a collection of distinct integers, without any duplicates, that fall within the range of 0 and a specified number. Specifically: var limit = 10; var amount = 3; Is there a way to leverage Javascript in order to produce 3 uniqu ...

Looking for a way to dynamically append a child element within another child

Struggling to include a new child within a specific child in Json myObject:any[] = []; this.myObject = { "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, } } addF ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

Learn the art of incorporating items and attributes into HTML through JavaScript or jQuery by extracting information from a csv or json file

As someone who is not a web developer, I am seeking to enhance the maintainability of the code below. My idea is to simplify the process using an appropriate method. I aim to dynamically inject content and attributes into an HTML file by utilizing either ...