Finding the maximum value of every row in 2D array C++ - c++

I've managed to find the minimum value of every row of my 2D array with this
void findLowest(int A[][Cm], int n, int m)
{
int min = A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] < min)
{
min = A[i][j];
}
}
out << i << " row's lowest value " << min << endl;
}
}
I'am trying to find the maximum value of every row using the same way,but it only shows me first maximum value
void findHighest(int A[][Cm], int n, int m)
{
int max = A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] > max)
{
max = A[i][j];
}
}
out << i << " row's highest value " << max << endl;
}
}
I can't find what's wrong with the second function and why is it only showing me the first maximum value it finds. Any help ?

Both functions return the result (maximum or minimum) for the whole array rather than each row, because you set max once rather than once per row. You can get the result for each row as follows:
void findHighest(int A[][Cm], int n, int m)
{
for (int i = 0; i < n; i++)
{
int max = A[i][0];
for (int j = 1; j < m; j++)
{
if (A[i][j] > max)
{
max = A[i][j];
}
}
// do something with max
}
}
or, even better, use the standard library function max_element:
void findHighest(int A[][Cm], int n, int m)
{
if (m <= 0) return;
for (int i = 0; i < n; i++)
{
int max = *std::max_element(A[i], A[i] + m);
// do something with max
}
}
This should give you all values which is easy to check:
#include <algorithm>
#include <iostream>
enum { Cm = 2 };
void findHighest(int A[][Cm], int n, int m) {
if (m <= 0) return;
for (int i = 0; i < n; i++) {
int max = *std::max_element(A[i], A[i] + m);
std::cout << max << " ";
}
}
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
findHighest(A, 2, 2);
}
prints 2 4.

If your compiler supports C++11, for concrete arrays you could use the following alternative, that's based on std::minmax_element:
template<typename T, std::size_t N, std::size_t M>
void
minmax_row(T const (&arr)[N][M], T (&mincol)[N], T (&maxcol)[N]) {
for(int i(0); i < N; ++i) {
auto mnmx = std::minmax_element(std::begin(arr[i]), std::end(arr[i]));
if(mnmx.first != std::end(arr[i])) mincol[i] = *(mnmx.first);
if(mnmx.second != std::end(arr[i])) maxcol[i] = *(mnmx.second);
}
}
Live Demo

Your test data is guilty for not clearly showing you the defect.
The row minima occur in decreasing values, so that they get updated on every row.
And the row maxima also occur in decreasing values, so that the first one keeps winning.
As others pointed, your function finds the global minimum/maximum, no the per-row extrema.
Move the initialization of the min/max variable inside the outer loop.

As mentioned your code only shows the maximum element in the whole array.
Here is the code which will help you.
void findHighest(int A[][Cm], int n, int m)
{
int max[n];
max[0]=A[0][0];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (A[i][j] > max[i])
{
max[i] = A[i][j];
}
}
cout << i << " row's highest value " << max[i] << endl;
}
}

{
int i,j;
int arr[4][2]={(1,2),(3,4),(5,6),(7,8)};
int max;
max=arr[0][0];
for( int i=0; i<4; i++)
{
for(int j=0; j<2; j++)
{
if(max<arr[i][j])
{
max=arr[i][j];
}
}
}
int min;
min=arr[0][0];
for(int i=0; i<4; i++)
{
for(int j=0; j<2; j++)
{
if(min>arr[i][j])
{
min=arr[i][j];
}
}
}
cout<<"maximum number is:"<<max;
cout<<endl;
cout<<"Minimum Number is:"<<min;
}

Related

Find the index of the largest element

The problem with my code is that it is not identifying my function, I am not sure if the function is incorrect or written with the wrong syntax. What I have tried is to create a new array for the location of the largest index but it doesn't seem to work.
#include <iostream>
#include <iomanip>
using namespace std;
void locateLargest(const double a[][4], int location[]);
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;
int main(){
int location [ROW_SIZE][COLUMN_SIZE];
double matrix [ROW_SIZE][COLUMN_SIZE];
double input;
cout<<"Enter the array: "<< endl;
for (int i = 0; i < ROW_SIZE; i++){
for(int j = 0; j < COLUMN_SIZE; j++){
cin>>input;
matrix[i][j] = input;
}
}
for(int i = 0; i < ROW_SIZE; i++){
for(int j = 0; j < COLUMN_SIZE; j++){
cout<< setw(4)<<matrix[i][j]<< " ";
}
cout<< endl;
}
locateLargest(matrix, location)
}
You can keep track of the max value's indices while iterating through the matrix.
void max_idx(const double (&arr)[RS][CS]) {
double curr_max = arr[0][0];
size_t max_i = 0, max_j = 0;
for (size_t i = 0; i < RS; ++i) {
for (size_t j = 0; j < CS; ++j) {
if (curr_max < arr[i][j]) {
curr_max = arr[i][j];
max_i = i;
max_j = j;
}
}
}
cout << "Largest value is at (i=" << max_i << ", j=" << max_j << ")\n";
}
Demo
First of all, you have to make sure that your code is consistent : in the prototype of your locateLargest function, location is a one-dimensional array but in your main() function it is a two-dimensional one.
This is how I would write this :
#include <iostream>
#include <iomanip>
using namespace std;
void locateLargest(double** a, int* location);
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;
int main()
{
int location [2];
double* matrix [ROW_SIZE];
for(int s= 0; s< ROW_SIZE; s++)
{
matrix[s]= new double[COLUMN_SIZE];
}
double input;
cout<<"Enter the array: "<< endl;
for (int i = 0; i < ROW_SIZE; i++)
{
for(int j = 0; j < COLUMN_SIZE; j++)
{
cin>>input;
matrix[i][j] = input;
}
}
for(int i = 0; i < ROW_SIZE; i++)
{
for(int j = 0; j < COLUMN_SIZE; j++)
{
cout<< setw(4)<<matrix[i][j]<< " ";
}
cout<< endl;
}
locateLargest(matrix, location);
}
void locateLargest(double** a, int* location)
{
int i, j;
double maxVal= a[0][0]; location[0]= location[1]= 0;
for(i = 0;i < ROW_SIZE; i++)
{
for(j = 0; j < COLUMN_SIZE; j++)
{
if(maxVal < a[i][j])
{
location[0] = i;
location[1]= j;
maxVal= a[i][j];
}
}
}
cout << "The location of the largest element is at ("<< location[0] << " , "<<
location[1] <<" ) . it is : "<< maxVal<<endl;
}
max represents the maximum value of your matrix's elements, you first set it to be equal to the first element and then compare it to each element of the matrix. Each time you find an element that is larger than max, you assign his value to max and his position to location and at the end of the iterations, you have the largest value and his location.

Problem in rearranging rows and columns of an array

In general, given the task:
A permissible matrix transformation is a permutation of two adjacent rows or two neighboring columns. A real square matrix of order n (n <= 12) is given. Using valid converters, you can get a matrix in which the maximum element is in the upper left corner. Elements were used to perform valid conversions.
My problem is precisely that I cannot swap adjacent rows or columns.
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
const int rows = 4, cols = rows;
int iMax = 0;
int jMax = 0;
int arr[rows][cols];
void arr_f()
{
setlocale(LC_ALL, "rus");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << " " << arr[i][j] << "\t";
if (arr[i][j] > arr[iMax][jMax])
{
iMax = i;
jMax = j;
}
}
cout << endl;
}
cout << endl << "The maximum number of array: " << arr[iMax][jMax] << endl << endl;
}
int main()
{
arr_f();
system("pause");
}
Tried to add features
inline void swap_columns(const int f, const int s)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[i][f], arr[i][s]);
}
}
inline void swap_rows(const int f, const int s)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[f][i], arr[s][i]);
}
}
and add the following to the arr_f () function:
swap_rows(0, iMax);
swap_columns(0, jMax);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << " " << arr[i][j] << "\t";
}
cout << endl;
}
But in this case, the rows (and columns) do not change as expected (the row in which the maximum value is located is immediately replaced by the first row, ignoring the rest).
You obtained a wrong result, because swap_columns and swap_rows make operations that are not allowed. You need to make them this way:
inline void swap_columns(const int k)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[i][k], arr[i][k+1]);
}
}
inline void swap_rows(const int k)
{
for (int i = 0; i < rows; ++i)
{
swap(arr[k][i], arr[k+1][i]);
}
}
And apply this way:
for (int k = iMax-1; k >= 0; --k)
swap_rows(k);
for (int k = jMax-1; k >= 0; --k)
swap_columns(k);
Certainly, this may be improved by moving larger blocks, but this is a matter of optimization.
To swap adjacent rows and columns, just replace this:
swap_rows(0, iMax);
swap_columns(0, jMax);
with this:
swap_rows(iMax + 1, iMax);
swap_columns(jMax + 1, jMax);
However, it is not clear from the problem description, whether this would always be the desired solution. And if iMax happens to be the last row index, then iMax + 1 would be out of bounds and fail at run time. In that case, perhaps iMax - 1 would be required instead.

Hollerith's Radix Sort

I have implemented the normal Radix Sort:
#include <iostream>
using namespace std;
void print(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int findMax(int arr[], int n) {
int mx = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
const int m = findMax(arr, n) + 1;
int C[m];
for (int i = 0; i < m; i++) {
C[i] = 0;
}
for (int i = 0; i < n; i++)
C[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
C[i] += C[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[C[(arr[i] / exp) % 10] - 1] = arr[i];
C[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
void radixSotr(int arr[], int n) {
int m = findMax(arr, n);
for (int exp = 1; m / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << endl;
cout << "Unsorted version of the array: " << endl;
print(arr, n);
cout << endl;
cout << "Sorted version of the array: " << endl;
radixSotr(arr, n);
print(arr, n);
return 0;
}
Now I am trying to implement Hollerith's version of Radix Sort, where the Radix Sort starts with the most significant bit and propagates iteratively to the least significant bit. Could you give me any ideas how to modify my code, because I am stuck.
Your countingSort function has a problem:
you should use an array of 10 indexes for counting instead of finding the largest element and declaring int C[m]. Your current code allocates a potentially huge array in automatic storage, invoking undefined behavior.
Here is a corrected version:
void countingSort(int arr[], int n, int exp) {
int output[n];
int C[10] = { 0 };
for (int i = 0; i < n; i++)
C[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
C[i] += C[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[--C[(arr[i] / exp) % 10]] = arr[i];
C[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
Note that this algorithm cannot sort an array with negative numbers.
The Hollerith algorithm uses least significant digit to most significant digit. It was invented for sorting US Census data tabulated on punched cards using tabulating machines. This is a very early example of computing for data processing that goes back to 1887. Punch cards used 2 different character encoding schemes named H-code and T-code all the way to the end of the 20th century, H standing for Herman Hollerith, inventor of these sorting machines, who died in 1929. (see http://ed-thelen.org/comp-hist/Knuth-Sort.html )
For the most significant bit down to the least significant bit, you need recursion, not an iterative method like the one you have:
Find the maximum value, hence the maximum exponent to get the most significant digit.
Sort the array according to the current digit
For each bucket of elements with the same digit at the current position:
if the bucket is empty or has only one element, it is sorted
otherwise, recurse on the bucket for the next lesser digit, using exp/10.
You can do this with any base >= 2.

Incorrect Result from Selection Sort Algorithm

#include <iostream>
using namespace std;
// Selection Sort function.
// Parameter 'a' is the size of the array.
void ss(int AR[] , int a) {
int small;
for (int i = 0 ; i <a ; i++) {
small = AR[i];
for (int j = i+1 ; j <a ; j++) {
if (AR[j]< small) {
int k = AR[j];
AR[j] = AR[i];
AR[i] = k;
}
}
}
}
int main() {
cout << "Enter the size of Your Aray";
int a;
cin >> a;
int AR[a];
cout << endl;
for (int i = 0; i < a; i++) {
cin >> AR[i];
cout << endl;
}
ss(AR, a);
cout << "The Sorted Array is";
for (int i=0; i < a; i++) {
cout << AR[i] << " ";
cout << endl;
}
}
When I enter the following:
15
6
13
22
23
52
2
The result returned is:
2
13
6
15
22
23
52
What is the bug preventing the list from being sorted numerically as expected?
The function can look like
void ss ( int a[], size_t n )
{
for ( size_t i = 0 ; i < n ; i++ )
{
size _t small = i;
for ( size_t j = i + 1; j < n ; j++ )
{
if ( a[j] < a[small] ) small = j;
}
if ( i != small )
{
int tmp = a[small];
a[small] = a[i];
a[i] = tmp;
}
}
}
It doesn't seem to be the SelectionSort I know. in the algorithm I know during every loop I look for the smallest element in the right subarray and than exchange it with the "pivot" element of the loop. Here's the algorithm
void selectionSort(int* a, int dim)
{
int posMin , aux;
for(int i = 0; i < dim - 1; ++i)
{
posMin = i;
for(int j = i + 1; j < dim; ++j)
{
if(a[j] < a[posMin])
posMin = j;
}
aux = a[i];
a[i] = a[posMin];
a[posMin] = aux;
}
}
and it seems that you change every smaller element you find, but also change the position of the "pivot". I hope the answer is clear.
Everything is ok in the original function, only that the small variable need to be refreshed when two vector elements will be switched.
Also in if statement set the small variable to the new value of AR[i].

Replacing values in a 2D array

I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?
If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.
You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.
The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)