TITLE: Optimize table layout
QUESTION [11 upvotes]: I have a set of cells arranged in a table. I need to minimize the table's height by adjusting column widths.
Each cell has an area such that its area is not encroached upon as its width and height are adjusted. In other words, given a final row height $h_i$, final column width $w_j$, and initial cell area $a_{ij} \in A$, this must hold true:
$$ \forall a_{ij} \in A : a_{ij} \leq h_i \cdot w_j $$
Since it's a table, each cell in a column has the same width and each cell in a row has the same height. Additionally, each row has the same width which is a chosen parameter $W$ (the width of the table). Thus:
$$ W = \sum_j w_j $$
...and the table will have this overall height:
$$ H = \sum_i h_i $$
So given $A$ (and knowing its dimensions), I need to compute all $w_j$ such that $H$ is minimized.
Minimum height of two-column table
Consider a two-column table with cell areas like the below. For simplicity, the table has a total width of 1. $p$ is the width of the first column; $1-p$ is the width of the second column; and column widths cannot be zero (so $0 < p < 1$):
  p  1-p
|<->|<->|

+---+---+
| a | b |
+---+---+
| c | d |
+---+---+
| e | f |
+---+---+
|...etc |

The height of the first row will be:
$$ \cases{
 p \leq \frac{a}{a+b} : \frac{a}{p}
 \\ p > \frac{a}{a+b} : \frac{b}{1 - p}
} $$
...and of the second:
$$ \cases{
 p \leq \frac{c}{c+d} : \frac{c}{p}
 \\ p > \frac{c}{c+d} : \frac{d}{1 - p}
} $$
...and so on. Notice how the left cell's area is considered (with one denominator) when $p$ is small enough; otherwise the right cell's area is used (with a different denominator).
Let's suppose that things are such that for a given $p$ these cells' areas are used: $( 
a, d, e, \ldots )$. This would be the table's height:
$$ \frac{a}{p} + \frac{d}{1 - p} + \frac{e}{p} + \ldots $$
Let's take a moment to generalize this. Add up all the areas chosen from the left side and call that $l$, and $r$ for all areas from the right side. Thus:
$$ H = \frac{l}{p} + \frac{r}{1 - p} $$
Now we want to minimize the table's height by finding the best $p$. So take the derivative and set it to zero:
$$ 0 = \frac{d}{dp} H = \frac{r}{(1-p)^2} -\frac{l}{p^2} $$
$$ = r \cdot p^2 - l \cdot (1 - p)^2 $$
$$ = (r - l) \cdot p^2 + 2l \cdot p - l $$
Here are the solutions to this quadratic equation:
$$ p = \cases{
 l \neq r : \frac{-2l \pm \sqrt{4l^2 +4l(r-l)}}{2(r - l)}
 \\l = r : 0.5
}$$
Plug each of the solved $p$ back into $H$ to figure out which is best.
So now all you have to do is decide, for a given range of $p$, which cells contribute to $l$ and which cells contribute to $r$, and then use the above equations. The best table height from all ranges of $p$ is the global minimum table height.
I say "for a given range of $p$" because for every row we know the range of $p$ for which the left cell should be considered versus the right cell. For example, we know that cell $a$ should be added to $l$ when $p \leq \frac{a}{a + b}$. That means the first row contributes two possible ranges of $p$ that need to be checked (and $\frac{a}{a + b}$ is the boundary). The second row contributes another two possible ranges (with the boundary at $\frac{c}{c + d}$). And so on. In each range different cell areas are contributing to $l$ and the rest are contributing to $r$.
In other words, if there are $x$ table rows then there are up to $2x$ different equations for $H$ that you need to solve to find the minimum height of a two-column table.
But I do not know how to generalize this into more columns
False starts
#1
Here's an algorithm which at first glance might seem to do the trick. But it only works for certain table configurations. For example, this does not work when the diagonal cells begin as "king" cells.

Lay out the table so that all rows are tightly stacked (meaning no row exists in which all cells in that row have elbow room). At this point it doesn't matter how wide the table is. As a consequence of this some columns will be too wide
Select the first column
For every cell in the column, calculate the amount the column can be shrunk $\Delta w = w_y - a_i / h_x$ such that this cell will have no elbow room
Find the minimum $\Delta w > 0$ (if any) of the column
Shrink the column by that amount
Select the next column and repeat from #3 until all columns have been adjusted
Scale the table to the desired width, preserving relative column proportions
Recalculate row heights based on the final column widths

This comes from the intuition that when a table's rows all have minimum height then each row will have at least one "king" cell which has no elbow room and will only increase that row's height if its column is collapsed further. Therefore the table has to get taller if any "king" cell's column is shrunk. But that only covers columns in which a "king" cell is present. The goal of this algorithm is to get "king" cells in all columns.
Once there's a "king" cell in each row and in each column then one would think that no column can be shrunk without a net increase in table height. One would think that increasing a row's height cannot be compensated by a decrease in another row's height because one would think all other rows already have minimum height.
But that's an incorrect intuition. While it may be true that no column may be shrunk in isolation, there may still exist the possibility to alter the widths of several columns together in such a way that the total table height is reduced.
Regardless, I do believe it's the case that the optimal column widths are still optimal when scaled together. So I believe steps 7 and 8 are valid.
To illustrate why this algorithm does not work, consider this 2x2 table:
+---+---+
| a |   |
+---+---+
|   | b |
+---+---+

In this case, the table has two empty cells on one diagonal and two populated cells on the other diagonal. Thus these two cells are guaranteed to be king cells, and the algorithm will traverse the columns without altering anything. In other words, the original column arrangement (whatever that happens to be) is the final column arrangement. The algorithm does nothing but push the problem of optimizing table layout elsewhere.
In this specific case it's possible to demonstrate that the ideal ratio of first column width to second column width is $\sqrt{a} : \sqrt{b}$. Yet this isn't the ideal ratio for all tables. So the problem remains unsolved in general.
#2
Given that the optimal column distribution for a two-column table may be found in O(rows^2) time (see above), I was hopeful for an easy way to append columns. But this doesn't appear to be feasible.
To illustrate this, consider this optimal table (roughly at scale):
+-+-------------+
|1|             |
+-+-------------+
| |             |
| |             |
| |     169     |
| |             |
| |             |
+-+-------------+

Since it's optimal, the first row height is $\sqrt{1} / \sqrt{169} = 7.7\%$ of the table height.
What happens when we append the following column to it?
+-----+
| 1e6 |
+-----+
|  0  |
+-----+

169 is peanuts compared to 1e6. And what are we going to do—place it in a row that's only 7.7% of the total table height while the other 92.3% goes to the cell with 169? Of course not! We'll want to give the second column proportionally more space so that it gets shorter and the 1e6 can grow taller/skinnier. And as the 1e6 grows taller we can give the first column proportionally less space (so that the height of the 1 is equal to the height of the 1e6).
In other words, appending a column requires laying out the entire table again. Meaning to lay out a three-column table you need to know how to lay out a three-column table. That doesn't really get us anywhere. And for the general case I think that would work out to O(rows^2 * columns!) time complexity.

REPLY [2 votes]: Here is just the code that is (presumably) finding the exact answer for not too large matrices. All explanations will come later. Again it is in Asymptote. Why not in C? I know C++ but having a slow computer with an interpreted rather than compiled language allows you to watch the program as it goes (if you bother to output the work protocol to the screen, of course) and see many nuances that otherwise would be easily missed. I found at least 6 logical bugs in the original version this way (I hope the remaining number is less). The progress is not linear because the program tries to locate what Matt calls "king cells" in the matrix and the "vert=" line is a better mark of progress than the difference between the upper and the lower bounds. The final array of widths is $P$ and the program terminates when the relative error is $10^{-15}$ (be careful here: due to the rounding errors it may continue to run beyond that point, but once you see "no conflict" and "nothing to do" repeating again and again, the job is actually done and you are watching the geometric convergence game end (which can be also played differently, but who cares?).
srand(seconds());

int m=30, n=17, K=100001, k, SK=10, Count=0, proccnt=0, Failtime=1000000, I=0,J=0, cycletime=0; 
real M=0, Mdel=0, TTT=0, B;
int time=0, failtime=0, successtime=0; 
int tt=1, ttt=1, blcount=0, ulttol=3;


int start=seconds();

int[][] blacklist;
for(int i=0;i<m;++i) blacklist[i]=array(n,1);

real[][] a, aaa,  b , bb, bbb, db, dbb, bres;
real[] AA;

/// Initiating the matrix ////////////

real delta=0.0001;

for(int i=0;i<m;++i)
{
real u=unitrand(), v=unitrand();
a[i]=new real[]; b[i]=new real[];
for(int j=0; j<n; ++j) 
{
a[i][j]=1+delta*sin((i+j^2)); 
b[i][j]=1/n;
}
//a[rand()%(i+1)][rand()%n]=2;
//a[i]*=unitrand();
}

////////////////////////////////////////////


aaa=copy(a); bres=copy(b);
real kill=1/1000;



int [][] temp; bool[] conf=array(n,true); 
bool fast=true, notreset=true, confl=true;

for(int i=0;i<m;++i) temp[i]=array(n,0);

int[] Ind; for(int i=0;i<m;++i) Ind[i]=i;

real Norm(real[][] b)
{
real[] S;
for(int j=0;j<n;++j)
{
real s=0; for(int i=0;i<m;++i) s+=a[i][j]*b[i][j]; S[j]=s;
}
return sum(map(sqrt,S))^2;
}


void shuffle()
{
for(int kk=0;kk<m;++kk) {int a=rand()%m, b=rand()%m; int II=Ind[a]; Ind[a]=Ind[b]; Ind[b]=II;}
}

bool[] conflict(real[][] b)
{
bool[] conf=array(n,false);

int count=0; 

for(int i=0;i<m;++i) 
{
if(min(b[i])<0) {write("karaul"); pause();}
b[i]=max(b[i],array(n,0));
count+=sum(map(sgn,b[i]));
}
int[] pres=array(m,1);
int[][] sb;
for(int i=0;i<m;++i) {sb[i]=map(sgn,b[i]); sb[i][n]=1;}


for(int I=1;I<m;++I)
for(int i=0; i<I; ++i)
{
if(pres[i]>0 && sum(sb[i]*sb[I])>sb[i][n]*sb[I][n]) {pres[i]=0; sb[I]=sb[i]+sb[I];}
}

int vert,edgecnt,Vert=0,Edgecnt=0; int comp=sum(map(sgn,pres));
for(int i=0;i<m;++i) 
{
if(pres[i]>0) 
{
vert=sum(sb[i])-sb[i][n];
Vert+=vert;
edgecnt=-sb[i][n];
for(int j=0;j<n;++j) edgecnt+=max(2*sb[i][j]-1,0); 
Edgecnt+=edgecnt;
if(edgecnt>vert-1) for(int j=0;j<n;++j) {if(sb[i][j]>0) conf[j]=true;}
}
}
int alive=0; for(int i=0;i<m;++i) for(int j=0;j<n;++j)
if(conf[j] && b[i][j]>0 && blacklist[i][j]<=ttt) ++alive;
write("vert="+string(Vert)+"("+string(alive)+") edgecnt="+string(Edgecnt)+" comp="+ string(comp));
return conf;
}





real[] p, P, S;

for(k=0;k<K;++k)
{

void procedure()
{
for(int j=0;j<n;++j)
{
real s=0; for(int i=0;i<m;++i) s+=aaa[i][j]*b[i][j]; S[j]=s;
}
for(int i:Ind)
{
real aa;
real[] A,V,C,B;
for(int j=0;j<n;++j) {A[j]=aaa[i][j]; V[j]=S[j]-aaa[i][j]*b[i][j]; C[j]=V[j]/aaa[i][j];}
real aa=(k==0?(sum(C)+1)/sum(A):AA[i]);

int countbound=40;

for(int j=0;j<n;++j) B[j]=max(aa*A[j]-C[j],0);
if(sum(B)>1/2)
{
if(sum(B)<1)
{
real sl=0;
for(int j=0;j<n;++j) sl+=A[j]*sgn(B[j]);
aa+=1.0001*((1-sum(B))/sl); countbound=4;
}
}
else aa=(sum(C)+1)/sum(A);

real da=1;
int count=0;

while(da>0 && count<countbound)
{
++count; 
//write(da,count); //pause();
for(int j=0;j<n;++j) {B[j]=aa*A[j]-C[j]; if(B[j]<0) {B[j]=0; A[j]=0; C[j]=0;}}
if(sum(A)>0) {da=sum(B)-1; aa-=da/sum(A);}
else {write("alert"); pause(); for(int j=0;j<n;++j) {if(b[i][j]>0) A[j]=aaa[i][j];} aa=(sum(C)+1)/sum(A); } 
//write(sum(B),aa,da,sum(A),sum(C));
}
for(int j=0;j<n;++j) {b[i][j]=B[j]; S[j]=V[j]+aaa[i][j]*B[j];}
Count+=count; 

if(abs(sum(b[i])-1)>0.1) {write("rough!"); pause();}
AA[i]=aa; b[i]/=sum(b[i]);
}
++proccnt;
}

bool check()
{
bool check=false;
for(int i=0;i<m && !check;++i) for(int j=0;j<n;++j) check=check || (bres[i][j]>0 && b[i][j]==0);
return check;
}




void fix()
{
for(int i=0;i<m;++i) for(int j=0;j<n;++j) 
{
if(b[i][j]==0 && conf[j]) aaa[i][j]=a[i][j]*kill;
//if(b[i][j]==0) blacklist[i][j]=1;
}
}


void advance(bool adv=true)
{
for(int kk=0;kk<(adv?ttt:tt)*SK;++kk) procedure(); bres=copy(b); if(adv) {write("advancing with speed "+string(TTT)); fix();}
}


void reset(bool hard=true)
{
if(!confl) write("nothing to do"); else write("RESETTING "+(hard?"HARD":"SOFT")); 
fast=true; if(hard) blcount=0;   
//shuffle();
aaa=copy(a); for(int kk=0;kk<(confl && hard?ttt:1)*SK;++kk) procedure(); 
if(confl && hard) ttt*=2;  
fix(); 
}

real minb=1, shift=0;

TTT=1;

while (TTT>1/3) 
{ 
TTT=0;
//bbb=copy(b); advance(false); 
bb=copy(b); advance(false); bres=copy(b);

for(int i=0;i<m;++i) 
{
db[i]=b[i]-bb[i]; 
//dbb[i]=bb[i]-bbb[i]; 
shift=max(shift,max(map(abs,db[i]))); temp[i]=array(n,0);
}

for(int i=0;i<m;++i) for(int j=0;j<n;++j)
{
if(b[i][j]>0 && db[i][j]<0 && bb[i][j]>0) 
{
real u=-db[i][j]/b[i][j];
//v=-dbb[i][j]/bb[i][j]; 
if(u>TTT && u>0 && aaa[i][j]>a[i][j]/2 && blacklist[i][j]<=ttt) {TTT=u; I=i; J=j; minb=min(minb,b[i][j]);}
}
}
tt=(confl?blacklist[I][J]:1);
if(TTT>1/3) advance(); 
else if(TTT==0 || blcount>ulttol) reset();
else write('\n \naccelerating from speed '+string(TTT)+
"; position=("+string(I)+","+string(J)+"); cycle count= "+string(2*tt*SK)); 
}

time=seconds()-start; if(time>Failtime) {write('\n\nTotal failure'); pause(); Failtime*=2;} 

write("time= "+string(time)+", cycling "+string(cycletime)+
" seconds, failures =  "+string(failtime)+ ", successes= "+string(successtime));

write("count="+string(Count/m/proccnt)); 

conf=conflict(b);

for(int j=0;j<n;++j)
{
real s=0; for(int i=0;i<m;++i) s+=aaa[i][j]*b[i][j]; S[j]=s; p[j]=sqrt(s);  
}

p/=sum(p); 
if(k==0) P=copy(p); 
write(Mdel); 

{
real s=0, sss=0; 
for(int i=0;i<m;++i)
{
real M=0; 
for(int j=0;j<n;++j) {real h=a[i][j]/p[j]; if(h>M) M=h;}
sss+=M;
}


for(int i=0;i<m;++i)
{
real M=0; 
for(int j=0;j<n;++j) {real h=a[i][j]/P[j]; if(h>M) M=h;}
s+=M;
}

if(sss<s) P=copy(p); 
write(s,s-Mdel); 
if(s-Mdel<1/10^15*s) {write("******it took "+string(seconds()-start)+" seconds******");
pause();}
}

confl=false; for(int j=0;j<n;++j) confl=confl || conf[j]; 
if(!confl) {write("no conflict"); reset();} else fix();

if(fast)
{
for(int i=0;i<m;++i) for(int j=0;j<n;++j)
{
if(conf[j] && b[i][j]>0 && bb[i][j]>0) 
{
real u=-db[i][j]/b[i][j]; 
//v=-dbb[i][j]/bb[i][j]; 
if(u>TTT/10 && aaa[i][j]>a[i][j]/2 && blacklist[i][j]<=ttt) temp[i][j]=1;
}
}
}

if(confl) temp[I][J]=1;

void loop()
{
bres=copy(b); Mdel=Norm(b); B=b[I][J]; if(B==0) B=1;

int cyclestart=seconds();

for(int i=0; i<m;++i) for(int j=0; j<n; ++j) if(temp[i][j]>0) aaa[i][j]=a[i][j]*kill;

for(int kk=0;kk<tt*SK;++kk) procedure(); 

if(b[I][J]>0 && confl) {write("Too weak killing!"); pause(); kill/=10;}

for(int i=0; i<m ;++i) for(int j=0; j<n; ++j) if(temp[i][j]>0) aaa[i][j]=a[i][j];

for(int kk=0;kk<tt*SK;++kk) procedure();

cycletime+=seconds()-cyclestart+1;

M=Norm(b); 
}

loop(); real rat=b[I][J]/B;

while (rat>0 && rat<0.9 && M>Mdel) {write("Repeating..."); loop(); rat=b[I][J]/B;}

if(confl && rat>0 && M>Mdel) {write("BLACKLISTING!"); blacklist[I][J]=2*ttt; ++blcount; if(blcount>0) reset((blcount>4?true:false));} 


int bl=0; for (int i=0;i<m;++i) 
bl+=sum(map(sgn,max(blacklist[i]-array(n,ttt),array(n,0)))); 
write(string(bl)+"  vertices blacklisted");


if(M>Mdel) 
{
if(rat==0) {fast=true; blcount=0;}
if(confl) write("Success!"+(b[I][J]==0?" Vertex is gone": "Vertex stays with ratio "+string(b[I][J]/B)+
" and abs value "+string(b[I][J])));
if(!check()) tt*=2; 
Mdel=M; successtime+=2*tt*SK; notreset=true;} 
else 
{
b=copy(bres); fast=false; failtime+=2*tt*SK;
blacklist[I][J]=2*tt;
if(confl) write("Failure! "+string(Mdel-M)+" short...");   
if (tt<ttt) tt*=2; else 
if (TTT>0 && confl) 
{
write("BLACKLISTING!"); blacklist[I][J]=2*ttt; ++blcount; if(blcount>0) reset((blcount>ulttol?true:false));
//write(tt,ttt); pause(); 
} 
else reset(); 
//else {tt*=2;}
}


}