给定每行按钮数量需要多少行?

时间:2012-01-13 01:38:50

标签: c++ algorithm math

我想布置X按钮。

一开始,Y项可以连续排列。 布置第一行后,下一行中只能显示Y - 1项,依此类推。

所以说我有13个按钮,第一行最多可以有6个按钮,我需要3行。第一个将有6个按钮,第二个5个按钮和3个2按钮。

由于

可以做什么算法:

int getRowCount(int startCols,int numItems);

我知道如果列数是常数的话怎么用MOD做,但如果每列的最大列数减少,你会怎么做呢?

1 个答案:

答案 0 :(得分: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,我会得到什么答案?

相关问题