I came up with an algorithm and I wanted to ask something. Is there any way to set a range of values within an array?
Eg
int N = 10;
int array[N] = {2,6,5,9,4,3,5,9,4,9};
and using a loop to increase the start value with each pass.
for (int A = 1; A < N - 2; A++) {
for (int B = 1; B < N - 1; B++) {
int ProfitA = Sum(array[0...A-1]);
int ProfitB = Sum(array[A...A+B-1]);
int ProfitC = Sum(array[A+B...N-1]);
}
}
So is there any way to set the range of values in each array using the above C -pseudocode?
No, C does not have such functionality built in. Moreover, there is no functionality to get the upper boundary of an array once you pass it to a function (so called "decaying to pointers").
There are two standard solutions to this problem:
The first approach would look like this:
int sum_array(int* array, size_t len) {
int res = 0;
for (size_t i = 0 ; i != len ; i++) {
res += array[i];
}
return res;
}
...
int ProfitA = sum_array(array, A);
int ProfitB = sum_array(array+A, B);
int ProfitC = sum_array(array+A+B, N-A-B);
the second approach would look like this:
int sum_array(int* array, int first, int last) {
int res = 0;
for (int i = first ; i <= last ; i++) {
res += array[i];
}
return res;
}
...
int ProfitA = sum_array(array, 0, A-1);
int ProfitB = sum_array(array, A, A+B-1);
int ProfitC = sum_array(array, A+B, N-1);