3

What is the best way in C++ to calculate the coordinate of a rectangle (hyper-rectangle) in n-dimension?

I have dimensions definition of the rectangle in a 1d vector like:

[min1, max1, min2, max2, ...., minN, maxN]

For example, in 2d the dimensions, the vector is

[min1, max1, min2, max2]

And the corner coordinates I am looking for are

[min1, min2], [min1, max2], [max1, min2], [max1, max2]

How do we do this for a hyper-rectangle in n-dimension?

Yuchen
  • 30,852
  • 26
  • 164
  • 234
zaza
  • 365
  • 2
  • 7
  • I did something similar when trying to make an N-dimensional game of life. You might find [this tiny repository](https://github.com/ktsiam/n-Dimensional-Game-Of-Life) useful (see game.hpp/.cpp) – Kostas Jul 16 '19 at 20:24
  • 3
    Could you show some code? Preferably a [mcve]. – Jesper Juhl Jul 16 '19 at 20:26
  • 2
    @JesperJuhl I just need an algorithm to calculate the coordinates. – zaza Jul 16 '19 at 20:55

1 Answers1

6

That hyper-rectangle has 2^N vertices.

To compute the coordinates of i-th vertex where i in [ 0 .. 2^N-1 ] interval, loop over bits in the i from 0 (lowest one) to N-1. If the bit is set, use maximum coordinate for that dimension, if that bit is 0, use minimum coordinate for that dimension.

For example, for cube N=3, it has 8 vertices.

The first one has index 0, 0b000, you’ll get minimum values for all 3 coordinates. The last one has index 7, 0b111, you’ll get maximum values for all 3 coordinates. The rest of the vertices are in between, you’ll get some combination of min and max coordinates.

Soonts
  • 20,079
  • 9
  • 57
  • 130