Dynamic array - size calculation
Greetings fella's! :biggrin:
I have been trying to tackle this programming exercise:
Given a number 'n', calculate and store the results of doing 3 bitwise operations: '&', '|','^' for each combination of (a,b) given that:
n : 2 <= n <= 1000
a : 1 <= a <= n
b : a + 1 <= b <= n.
I am supposed to save all results in a table for further processing (which is not relevant for this question).
I came up with this function (just the problematic part):
Code:
void calculate_bitwise_combinations(int n)
{
int bitwise_results[/*how do i calculate the size?*/];
for(int a = 1; a <= n; a++) {
for(int b = a+1, *it = &bitwise_results[a-1]; b <= n; b++) {
*it++ = (a&b);
*it++ = (a|b);
*it++ = (a^b);
}
}
/// further processing here
}
(I am using a pointer-iterator that updates automatically on each sub-loop, just for convenience).
The issue I've run across is to calculate the size of the dynamic array, I've tried 3*(n*(n-1)) and 3*(n*n) but as 'n' gets larger, it either overshoots or undershoots the size making it unnecessarily large or too short to store all possible results.
How would i (or you) go about calculating the size of the table fast and cheap?
(this is not for school or work, just for fun).
Thanks you in advance and have a good day. :cool: