2012-01-13 56 views
0

我想佈置X個按鈕。查找每行給定數量的按鈕需要多少行?

在開始時,Y項可以連續。 第一行排列後,只有Y - 1項可以出現在下一行,依此類推。

所以說我有13個按鈕,第一行最多可以有6個按鈕,我需要3行。第一個將有6個按鈕,第二個5個按鈕和3個2個按鈕。

感謝

什麼算法可以做到:

INT getRowCount(INT startCols,詮釋一個numItems);

我知道如何處理MOD,如果列數是恆定的,但如果每列的最大列數減少,你會怎麼做?

+1

問題是什麼? – pezcode 2012-01-13 01:44:35

+0

那麼你的問題在哪裏?你想到了什麼? – shinkou 2012-01-13 01:45:30

+0

你有多少個按鈕?如果'X'是一個很大的數字,我可以建議一個'O(log N)'算法,其中'N =列數'。 – 2012-01-13 22:14:59

回答

2

在這樣的情況下,我嘗試將英文翻譯成代碼。

int getRowCount(int startCols, int numItems) { 
    int currentCols = startCols; 
    int numRows = 0; 

    while (numItems > 0) {  // as long as items remain 
    numRows += 1;    // add another row 
    numItems -= currentCols; // reduce the remaining items by the current number of columns 
    currentCols--;   // reduce the number of columns by one 
    } 
} 

在某些邊緣情況下運行該場景總是最好的。問自己這樣的問題:

如果numItems爲0,我會得到什麼答案? 如果startCols爲0,我會得到什麼答案? 如果numItems == startCols會得到什麼答案?

相關問題