2009-12-08 140 views
1

我有一组不同宽度的列,我需要一个算法来重新调整它们的大小,使其大于它们所有宽度的总和。调整列大小算法

我想算法优先均衡的宽度。所以如果我有一个绝对巨大的值,那么这些列的宽度将大致相同。如果没有足够的空间,我希望较小的细胞被优先考虑。

任何专家的想法?我喜欢简单的东西如:

getNewWidths(NewWidth, ColumnWidths[]) returns NewColumnWidths[] 

回答

3

伪代码:

w = NewWidth 
n = ColumnWidths.count 
sort(ColumnWidths, ascending) 
while n > 1 and ColumnWidths[n-1] > (w/n): 
    w = w - ColumnWidths[n-1] 
    n = n - 1 
for i = 0 to n-1: 
    ColumnWidths[i] = w/n 

你需要添加一些代码来重新分配从W/N计算任何roundoffs,但我认为这会做。

+0

感谢。工作得很好。 – 2009-12-21 02:33:19

0

我会分解,在两个步骤,首先决定你有多少均衡的希望(0和1之间),并仅次于它适应新的总宽度。

例如在

def get_new_widths new_total, widths 
    max = widths.max 
    f = how_much_equalizing(new_total) # return value between 0.0 and 1.0 
    widths = widths.collect{|w| w*(1-f)+max*f} 
    sum = widths.inject(0){|a,b|a+b} 
    return widths.collect{|w| w/sum*new_total} 
end 

def how_much_equalizing new_total 
    return [1.0, (new_total/2000.0)].min 
end 
3

马克赎金的答案给出正确的算法,但如果你遇到问题搞清楚发生了什么事情在那里,这里是用Python实际实现:

def getNewWidths(newWidth, columnWidths): 
    # First, find out how many columns we can equalize 
    # without shrinking any columns. 
    w = newWidth 
    n = len(columnWidths) 
    sortedWidths = sorted(columnWidths) # A sorted copy of the array. 
    while sortedWidths[n - 1] * n > w: 
     w -= sortedWidths[n - 1] 
     n -= 1 

    # We can equalize the n narrowest columns. What is their new width? 
    minWidth = w // n # integer division 
    sparePixels = w % n # integer remainder: w == minWidth*n + sparePixels 

    # Now produce the new array of column widths. 
    cw = columnWidths[:] # Start with a copy of the array. 
    for i in range(len(cw)): 
     if cw[i] <= minWidth: 
      cw[i] = minWidth 
      if sparePixels > 0: 
       cw[i] += 1 
       sparePixels -= 1 
    return cw