Hi, How can i addition one + one matric (array data structure) and after it find the third smallest number in it in C language (not C++)? Thank you for the code.
A:
- First decide how to represent the matrix (hint: use an array of arrays)
- Then figure out how to add two matrices - this is simple
- Then, how do you find the 3rd smallest element in a sequence? There are many ways! Is efficiency especially important for you? What algorithmic complexity is required?
Eli Bendersky
2010-05-16 16:25:45
1) For example int mat1[50][50],mat2[50][50];2) I dont know how to do addition and after find the 3rd smallest element in the result and printf it - some kind of for cycle etc.
Heigan
2010-05-16 16:32:23
Is it even possible?
Heigan
2010-05-16 16:36:28
@Heigan: sure it's possible. Didn't you learn how matrix addition works? If not, try to find it online - should be very easy.
Eli Bendersky
2010-05-16 18:21:54
A:
If you are trying to access SIMD instructions, I don't believe there is an approach that will do both at the same time. If you are not trying to do use SIMD, then just keep a temp array of the three smallest values (like a priority queue) that is updated each time a sum is computed in the matrix.
If this were C++, the priority queue could be kept in a functor object used by the STL algorithms.
Brent Arias
2010-05-16 16:28:20
About your tip for keeping a temporary variable: note that it's somewhat more complex in his case since he seeks the 3rd smallest item, not *the* smallest item
Eli Bendersky
2010-05-16 16:30:57
A:
Example code follows:
void addMatrix(unsigned int size, double const * const a, double const * const b, double * const res) {
int i;
for (i = 0; i < size * size; ++i)
res[i] = a[i] + b[i];
}
double findThirdSmallest(unsigned int size, double const * const input) {
//save the three smallest values inside res
double res[3];
int i;
for (i = 0; i < 3; ++i) {
res[i] = LDBL_MAX;
}
for (i = 0; i < size * size; ++i) {
int j;
for (j = 0; j < 3; ++j) {
if (input[i] < res[j]) {
int k;
for (k = 2; k != j; --k) {
res[k] = res[k - 1];
}
res[j] = input[i];
break;
}
}
}
return res[2];
}
EDIT: Changing the type and the size of the matrix will be your work.
ablaeul
2010-05-16 17:52:41
And if i have int mat1[50][50],mat2[50][50] is is really nessesary to use double and LDBL_MAX ? Thx
Heigan
2010-05-16 18:07:12