views:

50

answers:

1

Hi, How do you find number of items in a column inside a grid?

I have a grid (listview control to be specific), and have some items. Some times a given row might not be full. ANd can have values in fewer than maximum columns. I need to find Number of items in a given Column.

If the grid is like

1   2   3
4   5   6
7       

and if input column is 1, then we need to output 3, and 2 for input of 2 or 3.

I have variables to for ItemCount, CoulmnCount and RowCount which track number of items, rows and columns.

A very rudimentar way would be something like this:

int iItemCount=0,iItemInColumn=0;
for(int iCol=0;iCol<iColumnCount;iCol++)
    for(int iRow=0;iRow<iRowCount;iRow++,iItemCount++)
        if(iCol==iInputCol && iItemCount<iTotalItems)
            iItemInColumn++;

Can you guys think of any sophesticated way, which does not need loops? possible utilizing just 3 variables which I already have for tracking?

+1  A: 

Assuming 0-based indexes:

def itemsInColumn(itemCount, columnCount, inputColumn):
  lastItemColumn = (itemCount - 1) % columnCount
  if inputColumn <= lastItemColumn:
    return (itemCount + columnCount - 1) / columnCount
  else:
    return itemCount / columnCount

It depends on the total number of items (itemCount) and the number of columns (columnCount). It just computes itemCount / columnCount, and rounds up or down depending on whether the input column is less than or equal to the last item's column.

The computation "(itemCount + columnCount - 1) / columnCount" is just a trick for rounding up using integer division. In general, given positive integers a and b: ceil(a / b) = (a + b - 1) div b, where div is integer division.

Sheldon L. Cooper
Thank you for the answer.For the example given, itemCount=6, columnCount=2 right? With your formula for inputColumn=0:lastItemColumn=0, return value 3, which is correct.But for inputColumn=1 or 2:lastItemColumn=0, return value is still 3, which is incorrect.Am I missing something in follwoing your logic?
Adarsha
No, your examples would be: itemsInColumn(7, 3, 0), itemsInColumn(7, 3, 1) and itemInColumn(7, 3, 2), which result in 3, 2 and 2, respectively.
Sheldon L. Cooper
The columnCount is the number of columns. The only 0-based index in the input is inputColumn, whose precondition is: 0 <= inputColumn < columnCount.
Sheldon L. Cooper
Yup.. gotcha.. i got confused with all of them being zero based one's
Adarsha