2009-12-08 84 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