Find maximum, minimum, average of a matrix in C++ [closed]
How do I find the maximum, minimum and average values in a given matrix (matrix[i][j]
) in C++. The type is unsigned long double.
There's nothing clever to be done here (pseudocode only, since this smells like HW):
for each entry in the matrix:
add the entry to a running sum
compare the entry to a running min
if it's smaller, it's the new running min
compare the entry to a running max
if it's larger, it's the new running max
average is the sum divided by the number of entries
You can micro-optimize that loop to make it more or less efficient, but there's nothing you can do algorithmically to be more clever. You need to look at all i*j
entries no matter what.
Maybe this:
Maximum:
int maximum = 0;
for(int x=0; x<width; ++x)
for(int y=0; y<height; ++y)
maximum = std::max(matrix[x][y], maximum);
Minimum:
int minimum = 0;
for(int x=0; x<width; ++x)
for(int y=0; y<height; ++y)
minimum = std::min(matrix[x][y], minimum);
Avarage:
int avarage = 0;
for(int x=0; x<width; ++x)
for(int y=0; y<height; ++y)
avarge += matrix[x][y];
avarge /= width*height;
Assuming matrix
is an actual C++ two-dimensional array could you use standard algorithms.
Untested code:
long double mean = std::accumulate(matrix[0], matrix[0] + i*j, 0.0) / (i*j);
long double matrix_min = std::min_element(matrix[0], matrix[0] + i*j);
long double matrix_max = std::max_element(matrix[0], matrix[0] + i*j);
Do note that this does extra passes over the matrix at the benefit of being clear what it's doing.
If it's another container type like a vector
of vector
s then you'd have to run the algorithms on each row and take the max of each row.
Loop through all the values, recording current max, min, and cumulative sum. Then divide the cumulative sum by the number of elements to get the mean.
精彩评论