2012-01-13 20 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会得到什么答案?

相关问题