Number of Items in a Column inside a grid - c++

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?

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.

Related

Fill the Grid with three colors A and B and C

How to find the numbers of ways to fill a grid (3*n)array, with three colors A, B and C.
Under the following constraints:
1) All the n cells of the same row can't have the same color.
2) All the 3 cells of the same column can't have the same color.
Sample input : if n=2, then output or number of ways = 174.
Please explain the approach for this.
This answer given by sam29 on codefores.
We can solve this question using Inclusion-Exclusion principle. So, let's first consider only the first column of the matrix. We can easily deduce that there are 24 different ways to fill that column keeping in mind that we can't have the same letter in the complete column. Now, we can directly say that the total ways to fill the complete matrix will be 24^N (Name this value as X1). In this answer, we have made sure that all the column contains distinct alphabets. But we need to consider the cases a row contains the same letter. So, now we will use inclusion-exclusion principle.
Find the number of cases with one row same. Fix 'A' in the first row. Now, take only the first column and you can deduce that there are 8 distinct ways to fill the 2nd and the 3rd row of the first column keeping in mind we can't have the same letter in the complete column. So, now we can find the total number of ways to fill all the N rows as 8^N. Now, we can do the same thing with 'B' and 'C' in the first row and similarly, we can repeat the process for the 2nd and the 3rd row. So, the total number of ways will be 9*8^N (Name this value as X2).
Find the number of cases with two rows same (Name this value as X3). This is the trickiest part of the question. I'll explain this at last.
Find the number of cases with all the three rows same but we can't have the same letter in a single column. This is pretty easy and is equivalent to the number of ways to fill a single column and 3 rows. So, the answer is 24 for this scenario (Name this value as X4).
Now, the final answer will be X1-X2+X3-X4.
Now, coming back to the answer for 2nd scenario. So, we will try to find the answer for the case when the first row and second row is same and we can repeat that process for the 2nd row and 3rd row AND 1st row and 3rd row. Basically, we can multiply the answer we will calculate now with 3. Okay, now take only the first column. Now, you can see that there will be 2 scenarios, one will be when the first and second row contains the same letter and in that case, we have to place a different letter in the 3rd row because else we will violate our condition of the distinct column. So, the total number of ways in the first scenario will be 3*2^N (I have skipped some part but I have provided the exact reason and a little further thinking and you will get the solution). Now, for the next scene when the first and second row contains different letters. In that case, you can place any letter in the 3rd row. Again try to think a little more and you will get the answer as 6*3^N. So, the total answer will be 3*2^N + 6*3^N. And as I said before we need to multiply it by 3 (Number of ways to choose 2 rows from 3 rows). So, X3 will be 3*(3*2^N + 6*3^N).
The complexity is pretty direct, you can do precomputation or apply exponent function every time.
Thanks.
This is combinatorial question, for sure it is better to post questions like this on math.stackexchange.com.
A row can be in two different configurations: having two colors (ABA) and having three colors (ABC). If we have last row of some configuration, lets check possibilities for next row.
A | B B B C C
B | A A C A A
A | B C B B C
A | B B B C
B | A C C A
C | B A B B
Set:
A_n : number of dimension n matrices where last row is of ABA configuration,
C_n : number of dimension n matrices where last row is of ABC configuration,
X_n : number of dimension n matrices = A_n + C_n.
From upper list of possibile next row it holds:
A_n = 3 * A_(n-1) + 2 * C_(n-1) = 2 * X_(n-1) + A_(n-1)
C_n = 2 * A_(n-1) + 2 * C_(n-1) = 2 * X_(n-1)
=>
X_n = 4 * X_(n-1) + A_(n-1)
Result to question is X_n, for which calculation A_n is needed, and initial values are A_1=6, X_1=12.
Update:
Search in OEIS for values 2, 9, 41, 187 (upper sequence if colors are not important, real number divided by 6), produces sequence A020698. Sequence mentions similar problem, and suggests that upper recursion can be stated in simpler manner:
X_n = 4 * X_(n-1) + A_(n-1)
= 4 * X_(n-1) + A_(n-1) + X_(n-1) - X_(n-1)
= 5 * X_(n-1) + 2 * X_(n-2) + A_(n-2) - 4 * X_(n-2) - A_(n-2)
= 5 * X_(n-1) - 2 * X_(n-2)

To find the min and max after addition and subtraction from a range of numbers

I am having a Algorithm question, in which numbers are been given from 1 to N and a number of operations are to be performed and then min/max has to be found among them.
Two operations - Addition and subtraction
and operations are in the form a b c d , where a is the operation to be performed,b is the starting number and c is the ending number and d is the number to be added/subtracted
for example
suppose numbers are 1 to N
and
N =5
1 2 3 4 5
We perform operations as
1 2 4 5
2 1 3 4
1 4 5 6
By these operations we will have numbers from 1 to N as
1 7 8 9 5
-3 3 4 9 5
-3 3 4 15 11
So the maximum is 15 and min is -3
My Approach:
I have taken the lower limit and upper limit of the numbers in this case it is 1 and 5 only stored in an array and applied the operations, and then had found the minimum and maximum.
Could there be any better approach?
I will assume that all update (addition/subtraction) operations happen before finding max/min. I don't have a good solution for update and min/max operations mixing together.
You can use a plain array, where the value at index i of the array is the difference between the index i and index (i - 1) of the original array. This makes the sum from index 0 to index i of our array to be the value at index i of the original array.
Subtraction is addition with the negated number, so they can be treated similarly. When we need to add k to the original array from index i to index j, we will add k to index i of our array, and subtract k to index (j + 1) of our array. This takes O(1) time per update.
You can find the min/max of the original array by accumulating summing the values and record the max/min values. This takes O(n) time per operation. I assume this is done once for the whole array.
Pseudocode:
a[N] // Original array
d[N] // Difference array
// Initialization
d[0] = a[0]
for (i = 1 to N-1)
d[i] = a[i] - a[i - 1]
// Addition (subtraction is similar)
add(from_idx, to_idx, amount) {
d[from_idx] += amount
d[to_idx + 1] -= amount
}
// Find max/min for the WHOLE array after add/subtract
current = max = min = d[0];
for (i = 1 to N - 1) {
current += d[i]; // Sum from d[0] to d[i] is a[i]
max = MAX(max, current);
min = MIN(min, current);
}
Generally there is no "best way" to find the min/max in the performance point of view because it depends on how this application will be used.
-Finding the max and min in a list needs O(n) Time, so if you want to run many (many in the context of the input) operations, your approach to find the min/max after all the operations took place is fine.
-But if the list will hold many elements and you don’t want to run that many operations, you better check each result of the op if its a new max/min and update if necessary.

Finding how many rows needed given number of buttons per row?

I want to layout X buttons.
At the start, Y items can be in a row.
After the first row is laid out, only Y - 1 items can appear in the next row and so on.
So say I have 13 buttons and the first row can have up to 6 buttons, I would need 3 rows. The first would have 6 buttons the second 5 buttons, and the 3ed 2 buttons.
Thanks
What algorithm could be to do:
int getRowCount(int startCols, int numItems);
I know how to do it with MOD if the number of columns is constant but how would you do it if the maximum number of columns decreases with each row?
In situations like this, I try to translate the english into code.
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
}
}
It's always best to run through the scenario with some edge cases. Ask yourself questions like:
What answer do I get if numItems is 0?
What answer do I get if startCols is 0?
What answer do I get if numItems == startCols?

algorithm: find count of numbers within a given range

given an unsorted number array where there can be duplicates, pre-process the array so that to find the count of numbers within a given range, the time is O(1).
For example, 7,2,3,2,4,1,4,6. The count of numbers both >= 2 and <= 5 is 5. (2,2,3,4,4).
Sort the array. For each element in the sorted array, insert that element into a hash table, with the value of the element as the key, and its position in the array as the associated value. Any values that are skipped, you'll need to insert as well.
To find the number of items in a range, look up the position of the value at each end of the range in the hash table, and subtract the lower from the upper to find the size of the range.
This sounds suspiciously like one of those clever interview questions some interviewers like to ask, which is usually associated with hints along the way to see how you think.
Regardless... one possible way of implementing this is to make a list of the counts of numbers equal to or less than the list index.
For example, from your list above, generate the list: 0, 1, 3, 4, 6, 6, 7, 8. Then you can count the numbers between 2 and 5 by subtracting list[1] from list[5].
Since we need to access in O(1), the data structure needed would be memory-intensive.
With Hash Table, in worst case access would take O(n)
My Solution:
Build a 2D matrix.
array = {2,3,2,4,1,4,6} Range of numbers = 0 to 6 so n = 7
So we've to create nxn matrix.
array[i][i] represents total count of element = i
so array[4][4] = 2 (since 4 appears 2 times in array)
array[5][5] = 0
array[5][2] = count of numbers both >= 2 and <= 5 = 5
//preprocessing stage 1: Would populate a[i][i] with total count of element = i
a[n][n]={0};
for(i=0;i<=n;i++){
a[i][i]++;
}
//stage 2
for(i=1;i<=n;i++)
for(j=0;j<i;j++)
a[i][j] = a[i-1][j] + a[i][i];
//we are just adding count of element=i to each value in i-1th row and we get ith row.
Now (5,2) would query for a[5][2] and would give answer in O(1)
int main()
{
int arr[8]={7,2,3,2,4,1,4,6};
int count[9];
int total=0;
memset(count,0, sizeof(count));
for(int i=0;i<8;i++)
count[arr[i]]++;
for(int k=0;k<9;k++)
{
if(k>=2 && k<=5 && count[k]>0 )
{
total= total+count[k] ;
}
}
printf("%d:",total);
return 0;
}

generate a truth table given an input?

Is there a smart algorithm that takes a number of probabilities and generates the corresponding truth table inside a multi-dimensional array or container
Ex :
n = 3
N : [0 0 0
0 0 1
0 1 0
...
1 1 1]
I can do it with for loops and Ifs , but I know my way will be slow and time consuming . So , I am asking If there is an advanced feature that I can use to do that as efficient as possible ?
If we're allowed to fill the table with all zeroes to start, it should be possible to then perform exactly 2^n - 1 fills to set the 1 bits we desire. This may not be faster than writing a manual loop though, it's totally unprofiled.
EDIT:
The line std::vector<std::vector<int> > output(n, std::vector<int>(1 << n)); declares a vector of vectors. The outer vector is length n, and the inner one is 2^n (the number of truth results for n inputs) but I do the power calculation by using left shift so the compiler can insert a constant rather than a call to, say, pow. In the case where n=3 we wind up with a 3x8 vector. I organize it in this way (rather than the customary 8x3 with row as the first index) because we're going to take advantage of a column-based pattern in the output data. Using the vector constructors in this way also ensures that each element of the vector of vectors is initialized to 0. Thus we only have to worry about setting the values we want to 1 and leave the rest alone.
The second set of nested for loops is just used to print out the resulting data when it's done, nothing special there.
The first set of for loops implements the real algorithm. We're taking advantage of a column-based pattern in the output data here. For a given truth table, the left-most column will have two pieces: The first half is all 0 and the second half is all 1. Since we pre-filled zeroes, a single fill of half the column height starting halfway down will apply all the 1s we need. The second column will have rows 1/4th 0, 1/4th 1, 1/4th 0, 1/4th 1. Thus two fills will apply all the 1s we need. We repeat this until we get to the rightmost column in which case every other row is 0 or 1.
We start out saying "I need to fill half the rows at once" (unsigned num_to_fill = 1U << (n - 1);). Then we loop over each column. The first column starts at the position to fill, and fills that many rows with 1. Then we increment the row and reduce the fill size by half (now we're filling 1/4th of the rows at once, but we then skip blank rows and fill a second time) for the next column.
For example:
#include <iostream>
#include <vector>
int main()
{
const unsigned n = 3;
std::vector<std::vector<int> > output(n, std::vector<int>(1 << n));
unsigned num_to_fill = 1U << (n - 1);
for(unsigned col = 0; col < n; ++col, num_to_fill >>= 1U)
{
for(unsigned row = num_to_fill; row < (1U << n); row += (num_to_fill * 2))
{
std::fill_n(&output[col][row], num_to_fill, 1);
}
}
// These loops just print out the results, nothing more.
for(unsigned x = 0; x < (1 << n); ++x)
{
for(unsigned y = 0; y < n; ++y)
{
std::cout << output[y][x] << " ";
}
std::cout << std::endl;
}
return 0;
}
You can split his problem into two sections by noticing each of the rows in the matrix represents an n bit binary number where n is the number of probabilities[sic].
so you need to:
iterate over all n bit numbers
convert each number into a row of your 2d container
edit:
if you are only worried about runtime then for constant n you could always precompute the table, but it think you are stuck with O(2^n) complexity for when it is computed
You want to write the numbers from 0 to 2^N - 1 in binary numeral system. There is nothing smart in it. You just have to populate every cell of the two dimensional array. You cannot do it faster than that.
You can do it without iterating directly over the numbers. Notice that the rightmost column is repeating 0 1, then the next column is repeating 0 0 1 1, then the next one 0 0 0 0 1 1 1 1 and so on. Every column is repeating 2^columnIndex(starting from 0) zeros and then ones.
To elaborate on jk's answer...
If you have n boolean values ("probabilities"?), then you need to
create a truth table array that's n by 2^n
loop i from 0 to (2^n-1)
inside that loop, loop j from 0 to n-1
inside THAT loop, set truthTable[i][j] = jth bit of i (e.g. (i >> j) & 1)
Karnaugh map or Quine-McCluskey
http://en.wikipedia.org/wiki/Karnaugh_map
http://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm
That should head you in the right direction for minimizing the resulting truth table.