Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8691483
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:07:48+00:00 2026-06-13T00:07:48+00:00

Imagine a simple 2D grid; the objects on the grid can occupy more then

  • 0

Imagine a simple 2D grid; the objects on the grid can occupy more then one cell (but the points are always connected). Consider the following example, where I use letters A and B just to distinguish the objects (it is useful since the objects may be placed near each other):

0 1 2 3 4 5 6 7 8 9 10
1 . . . . . . . . . .
2 . . . . . . . . . .
3 . . . A . . . . . .
4 . . A A A . . B B .
5 . . . A . . . B B .
6 . . . . . . . . . .

I need an algorithm for the insertion of new objects that would position them on the grid and make sure they do not overlap. Thus, if I would like to embed a new object (denoted with C) and the coordinates of any of its cells would already be occupied, the algorithm should find the closest free region (i.e., list of points) to allocate the new object. Lets try to insert the object C at the coordinate (4, 3) which is already occupied by a cell from A:

0 1 2 3 4 5 6 7 8 9 10
1 . . . . . . . . . .
2 . C C . . . . . . .
3 . C C A . . . . . .
4 . . A A A . . B B .
5 . . . A . . . B B .
6 . . . . . . . . . .

As you can see, the object was moved to fit near the object A. I assume that the search should start around the occupied cell with the order (given in directions): N, E, S, W and after this in the middle directions: NE, SE, etc.

How would you suggest to implement this algorithm?

Update: The object position is the upper left point. And the closest point is obtained from the distance that is evaluated between the initial requested position and the surrounding free points.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:07:49+00:00Added an answer on June 13, 2026 at 12:07 am

    You want to iterate over possible displacements (i.e. shifts) in order of increasing distance. As all displacements are integers, the squared displacements need to be sums of two squares. The following python code keeps track of the next possible y displacement for each x displacement. It generates lists of pairs. Each pair denotes displacement coordinates. All elements in a single list have the same distance from the origin, whereas elements from later lists will have greater distance. So it doesn’t matter in what order you traverse the inner lists, at least in terms of distances. You might even want to randomize those.

    def iter_distance(maxr = 10):
        r = 0
        d = [0]
        while r <= maxr:
            m = maxr*maxr + 1
            for x, y in enumerate(d):
                sq = x*x + y*y
                if sq < m:
                    m = sq
                    b = []
                if sq == m:
                    b.append((x, y))
            for x, y in b:
                d[x] = y + 1
            if b[-1][0] == r:
                r += 1
                d.append(0)
            yield (b +
                   [(x, -y) for x, y in b if y] +
                   [(-x, y) for x, y in b if x] +
                   [(-x, -y) for x, y in b if x*y])
    
    for lst in iter_distance():
        marker = '*'
        for x, y in lst:
            print("{:5} {:5} {:10} {}".format(x, y, x*x + y*y, marker))
            marker = ' '
    

    The first lines of output look like this:

        0     0          0 *
        0     1          1 *
        1     0          1  
        0    -1          1  
       -1     0          1  
        1     1          2 *
        1    -1          2  
       -1     1          2  
       -1    -1          2  
        0     2          4 *
        2     0          4  
        0    -2          4  
       -2     0          4  
        1     2          5 *
        2     1          5  
        1    -2          5  
        2    -1          5  
       -1     2          5  
       -2     1          5  
       -1    -2          5  
       -2    -1          5  
        2     2          8 *
        2    -2          8  
       -2     2          8  
       -2    -2          8  
        0     3          9 *
        3     0          9  
        0    -3          9  
       -3     0          9  
    

    For distances up to 400 (i.e. passing 400 as the maxr argument), you’d get 502,625 lines for 37,556 different distances, so you want to generate these on the fly, not hard-code them into the application. You may however use these numbers to check your implementation, in case one of us made an error.

    If you are concerned about performance, you can use a priority queue instead of an array, and write it like this:

    #include <queue>
    #include <utility>
    #include <cmath>
    #include <iostream>
    #include <iomanip>
    
    class displacement {
    private:
      int _d;
      int _x;
      int _y;
    public:
      displacement() : _d(0), _x(0), _y(0) {}
      displacement(int x, int y) : _d(x*x + y*y), _x(x), _y(y) {}
      int x() const { return _x; }
      int y() const { return _y; }
      int sqd() const { return _d; }
      bool operator<(const displacement& d) const { return sqd() > d.sqd(); }
    };
    
    static void print2(int x, int y, int sqd) {
      std::cout << std::setw(10) << x << ' '
                << std::setw(10) << y << ' '
                << std::setw(20) << sqd << ' '
                << std::endl;
    }
    
    static void print1(int x, int y, int sqd) {
      print2(x, y, sqd);
      if (y)
        print2(x, -y, sqd);
      if (x) {
        print2(-x, y, sqd);
        if (y)
          print2(-x, -y, sqd);
      }
    }
    
    int main(int argc, char** argv) {
      int maxr = 400;
      int maxrsq = maxr*maxr;
      std::priority_queue<displacement> q;
      q.push(displacement(0, 0));
      while (q.top().sqd() <= maxrsq) {
        const displacement& d = q.top();
        int x = d.x();
        int y = d.y();
        int sqd = d.sqd();
        print1(x, y, sqd);
        q.pop();
        q.push(displacement(x, y + 1));
        if (x == y) {
          q.push(displacement(x + 1, y + 1));
        }
        else {
          print1(y, x, sqd);
        }
      }
    }
    

    In this case, the queue contains individual displacements, and the result will print individual displacements of the same distance in arbitrary (and probably implementation-defined) order, without collecting them into a list. Only the mirror images of a given displacement will be printed immediately. The code here employs full 8-fold symmetry, so the number of elements stored in the queue at any single time is even less than the maximal distance generated so far, except at the very beginning.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am having issues with what I can only imagine is a very simple
Imagine a simple, but large array with keys 0 to 100000. When doing a
Imagine the simple class line segment which it's constructor is are couple of objects
Imagine two simple java applications. Both of them are implementing the same JAR file
Imagine a simple page with a list of users. Selecting a user displays a
Imagine a simple case like this: class Book has_many :chapters end Let's say in
Imagine this simple form <form action=<?php echo $_SERVER['REQUEST_URI']; ?> method=post> <fieldset> <legend>Contact Me</legend> <label
excuse me for my ugly english) ! Imagine these very simple models : class
I imagine this has a rather simple answer <% for user in @users %>
imagine this html on a page <div id=hpl_content_wrap> <p class=foobar>this is one word and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.