views:

25

answers:

1

Hello! For example I have collection of blocks

Input:

    
[
 [name: "Block #1", x:0, y:0, width:4, height:1],
 [name: "Block #2", x:0, y:1, width:2, height:1],
 [name: "Block #3", x:2, y:2, width:2, height:1]
]

Output:

<table width="4" border="1">  
 <tr>    
  <td colspan="2" width="4" height="1">Block #1</td>  
 </tr>  
 <tr>    
  <td width="2" height="1">Block #2</td>  
  <td width="2" height="1">Block #3</td>  
 </tr>  
</table>

Any ideas for algorithm? Blocks not crossing.

+1  A: 

OP says position: absolute; is not an option ( http://jsfiddle.net/qCreh/1/ ), so tables it is.

(You want to use colspan and rowspan on tds, not width and height.)

If blocks were limited to 1 height, it'd be simple.
But they aren't, so you will have to calculate whether to add empty cells to use as left padding or not. Because of this behaviour:

<table>
<tr><td rowspan="2">I am at 0,0</td><td>I am at 0,1</td></tr>
<tr><td>1,1</td><td>I am at 1,1 and not 0,0 because of the previous rowspan!</td></tr>
</table>

So, an algorythm could be:

  1. Order the collection of blocks by row and then column;
  2. Prepare a list of "occupied cells" {(x1,y1), (x2,y2), etc};
  3. For each row;
  4. Get the next cell to fill;
  5. While you're not at the next cell to fill, if the cell is filled (check the list) skip it and remove this cell from the "filled list", if it is not filled add an empty td;
  6. Fill with a td with the proper rowspan/colspan for the block;
  7. If the td has rowspan/colspan, fill the list of occupied cells with the extra occupied cells (x1/y1, x1/y2, etc);
  8. If there are more cells in this row, go to next cell (4);
  9. If there are more rows, go to next row (3);
  10. End.

Note that you can affect the width of columns by using colgroup and col and setting widths on them.
table-layout: fixed; sounds sensible.

Is this a good solution?

ANeves
I can't use divs with absolute positioningSee: http://stackoverflow.com/questions/2919737/css-absolute-position-dont-work-in-ms-word
Tim
You're in for some trouble then, it'll be rough calculating which empty cells to add and which to skip. I'll try revamping my answer.
ANeves
Thanks a lot! I use your idea in my implementation. I can't vote for you answer. :(
Tim
But you can mark it as answer, if it did answer.
ANeves