Alignment puzzle

I have an array of N rectangles… the rectangles are in no specific order
what I need to do is move some of the rectangles so the when drawn they are equally spaced left to right

Assume an array R() as realbasic.rect

the rectangle with the smallest X won’t “move” as it would be the first one left to right
nor would the rectangle with the greatest Y+width as it would be the last one
only those between would move.

The widths of the rectangles may also vary… so it is the SPACE between them that needs to be calculated…and consistent

Just so I understand the problem, let’s say all the rectangles are of the same height and have the same starting y point. Let’s label the rectangles so that the leftmost starts at x0 and the rightmost ends at xn+wn. Let’s also say that the total space (x0 to xn+wn) is wide enough to accommodate the result without overlap. Are you ultimately wanting the space x1 - (x0+w0) to equal x2 - (x1+w1) to equal xn - (xn-1+wn-1)?

yes.

space 6,2,6

[*3*]<------>[*1*]<--->[*4*]<------>[*2*]

becomes
space 5,5,5

[*3*]<----->[*1*]<----->[*4*]<----->[*2*]

this is a simple example, as the width of the rectangles may not be equal, but the resultant space would be

think of the “Space Horizontal” feature in the Xojo IDE… different use, same concept

Based on this criteria, you would also have to assume that the total width of the rectangles does not exceed the right hand side of the right-most rectangle.

On that basis, the space will be found like this:

Find the leftmost rectangle.

LPOS= leftmost.left + leftmost.width

Find the rightmost

RPOS = rightmost.left

Using a loop , Sum the widths of all the other rectangles, and also count them

Space = ((RPOS-LPOS) - SUMOFWIDTHS) / (COUNTOTHERS+1)

Yeah… pretty much what I too came up with… it was just a matter of actually finding all those values within the subset of rectangles… and I kept dividing by the wrong “count”

Assuming your rectangles are in an array, or can be put into an array, create a custom sorter to sort them by position.

  • loop thru rectangles, accumlating width, and a pair array r.left:indx, as well as min(left) and max(right)
  • sort pair array by “left”, this gives the rectangles in left->right order
  • calculate space between as [right-left-total_width)/(# rect-1)
  • loop thru rectangles again … new left=min_left , min_left=min_left+width+space

rough, but those are basically the steps… and it seems to work out perfectly
Same process for Horizontal spacing, just use top and bottom values