What is the best way to transform specific [x, y] coordinates into intervals of [xstart, xend, ystart, yend]?

In my project, I have the ability to draw tiles on an x-y grid and paint a provided png image. The objective is to then save these tiles as a .json file.

Illustration of the issue:

https://i.sstatic.net/XUfoS.png

Currently, the JSON structure is created like this:

"woodenCrate":[[x,y],[x,y],[x,y]...]

However, I would like to transform it into:

"woodenCrate":[[xstart, xend, ystart, yend],[xstart, xend, ystart, yend]...]

This means consolidating individual points into larger chunks that can be drawn. My plan is to identify large rectangles within the data, and then repeat the process with the remaining pieces until only big rectangles and a few single-sized boxes remain.

The tiles are placed at integer positions in [x, y].

For example:

[[0,1],[0,2],[0,3],[1,1],[1,2][1,3]]

should be transformed into:

[[0,1,1,3]]

A solution that converts to

[[startX, startY, width, height]]
is also acceptable.

How should I go about solving this problem? I am using Javascript.

Answer №1

It has crossed my mind that simply encoding each individual row (or column) of the rectangles may be effective, especially if the rectangle dimensions are not excessively large.

Answer №2

I successfully tackled the challenge on my own.

Through my coding efforts, I was able to identify the largest possible rectangle within the given structure.

I then extracted that rectangle and repeated the process with the remaining part of the structure.

Although I ended up with a few 1x1 pieces, overall, my JSON file now contains fewer entries for the larger structures I created.

If you are interested in reviewing the code, you can find it in the "rangeOptimizer.js" file within my "tile-placer-v2" repository on GitHub. My username on both platforms is identical.

I understand that there may be more efficient solutions out there, but based on my analysis, this method effectively addresses my initial question.

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

implementing a SetTimeOut function following the clicking of a button

Hey there, I've been working on a code snippet that switches the display state from block to none with an onClick function. However, I'm looking to add a delay before the state change happens so that there's time for an animation effect to ...

retrieving a two-dimensional array without prior knowledge of its dimensions

As a beginner in utilizing pointers, I'm encountering an issue. I need to receive a 2D array of characters from the user, along with the number of rows and columns, and the specific content to fill the array with. int rows, col, i, j; char ** ...

Tips for finding the specific value's array index in PHP

I have retrieved the following array from a database: Array ( [0] => stdClass Object ( [cSize] => 120x60 [cFilename] => 29955_120x60.png [dtLastUpdated] => 2017-06-11T18:18:34-07:00 [cURL] => http:// ...

At times, Mongoose may return null, while other times it returns data frequently

I have designed a unique mongoose schema for managing contacts, with a custom defined ID. Here is the schema structure: const mongooseSchema = new mongoose.Schema({ _id:{ type:String, unique:true, required:true }, firstN ...

Any ideas why the React array filtering in my code is not functioning as expected?

In my React project, I am working on filtering a number of products and facing a simple issue. The array of filters (an array of strings) is stored in State with the default value of ["All"]. When another filter is clicked, this default value is replaced b ...

Symbol not located within the comparable array

I am working on creating a stack of comparable objects based on a specific interface. Within my class, here is the constructor I have implemented: public MyStack() { Comparable[] array = new Comparable[INITIAL_SIZE]; size = 0; } However, whenever I ...

generate radio buttons and corresponding labels in real-time

I am trying to automate the creation of elements for each record retrieved from my webservice. <label for="ZAALID_1">Zaal 1</label> <input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHK ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

What separates $(document).ready() from embedding a script at the end of the body tag?

Can you explain the distinction between running a JavaScript function during jQuery's $(document).ready() and embedding it in the HTML within script tags at the bottom of the body? Appreciate your insights, DLiKS ...

Is there a way to use a single function to fill and calculate multiple input fields with PHP, Javascript, and

I've encountered an issue while trying to populate a form using Javascript/ajax/php. The problem is that my function only fills in one of the required forms and then stops, even though I have received the second response from the server. Here's ...

Text that is selected within a contenteditable div: Find the beginning and end points of the highlighted text

<div contenteditable="true">This text is <b>Bold</b> not <i>Italic</i> right?</div> For instance, if the text appears in a bold format, but not italic and the user selects it, how can I determine the exact position ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? https://i.sstatic.net/y7Cs5.png Codesandbox: https: ...

Retrieve Django imagefield file name using jQuery before submitting

Exploring the essential Django image file upload procedure, where the image model incorporates the ImageField class. There's a custom display button replacing the default upload button which usually showcases the image name alongside it. Hence, the ne ...

Does the awaitMessages filter not execute the .then function?

I am currently implementing a direct message prompt in my bot, where the player must respond before the bot proceeds with further questions. I have set up a filter to prevent the bot from detecting and acknowledging its own message. However, for some reaso ...

typescript - transforming text into numerical values

newbalance = (Number(this.balance)) + (Number(this.pastAmount)); The result for my newbalance calculation is coming back as undefined, even though this.balance is 34 and this.pastAmount is 23. I've set this up in the controller and I'm trying t ...

Why is my Java Object Array throwing an InputMismatchException?

Having trouble with InputMismatchException while entering values at runtime. Check out the attached code and exception snapshot for more context. import java.util.Scanner; class ObjectArray { public static void main(String args[]) { Scann ...

The method of getJSON URL fails to function properly when invoked from an external JavaScript source

I'm grappling with a complicated issue and trying to determine if it's more closely tied to JSONP (JSON + padding) or something else entirely. Let's consider a file named example.php: <script src="jquery.js"</script> <script sr ...

I'm curious, in which environment does SvelteKit, Next.js, and Nuxt.js code execute? Also, is it possible to create HTTP request handlers within

My experience with using SvelteKit in my personal projects has been quite enjoyable. However, coming from a background of working with frameworks like Next.js and Nuxt.js, I often find myself confused about where the code I write actually runs. In my day ...

What advantages does useMemo offer over useCallback in this scenario?

From my understanding, the distinction between useCallback and useMemo lies in their usage based on whether a function/object/array or a primitive value is being returned. However, I came across an article on debouncing (found here: ) which suggested that ...

Updates to mousetrap key bindings are being reflected in the $scope object, but are not being detected by the

I have developed a function that updates a scope variable as shown below: // controller.js $scope.variable = 0; $scope.$watch('variable', function(){ console.log("change from watch"); }); $scope.increment = function(){ $scope.variable++; ...