wooproop
wooproop

Reputation: 39

How to swap 2d array columns in places?

How would I swap 2d array columns in places, but the swap has to happen between the columns that contain the smallest and biggest element in the 2d array. Any help on this would be appreciated.

#include <iostream>
#include <ctime>
#include <cstdlib>
#define rows 4
#define cols 4
using namespace std;



int main () {
    srand(time(0));
    int i=0, j=0,n,low,high,lowpos,highpos,a,b;
    int arr[rows][cols];
    
    for (i=0; i<rows; i++)
        for (j=0; j<cols; j++)
            arr[i][j] = 1 + (rand() % 200); 
    
    cout << "Random 2d generated array:" << endl;
    for (i=0; i<rows; i++){
        for (j=0; j<cols; j++)
            cout << arr[i][j] << " ";
        cout << endl;
    }
    
    
    
    
    high=arr[0][0];
    low=arr[0][0];
    for(i=0;i<rows;++i)
    {
    for(j=0;j<cols;++j)
    {
        if(arr[i][j]>high)
            high=arr[i][j];
        
        else if(arr[i][j]<low)
            low=arr[i][j];
            
    }
    }       
    cout<<"\nBiggest element:"<<high<<"\nSmallest:"<<low<<"\n";
    
}


Upvotes: 0

Views: 57

Answers (1)

KornelMrozowski
KornelMrozowski

Reputation: 36

I decided to stay in c++11 standard. Of course swap helps do the trick.

#include <cstdlib>
#include <iostream>
#include <iomanip>

#define rows 4
#define cols 4
using Arr = int[rows][cols];

std::pair<int, int> high_low_ids(const Arr arr, int nrow = rows, int ncol = cols) {
    int highpos = 0, lowpos = 0;
    int high = arr[0][0];
    int low = arr[0][0];
    for(int i = 0; i < nrow; ++i)
        for(int j = 0; j < ncol; ++j)
            if(arr[i][j] > high) {
                highpos = j;
                high=arr[i][j];
            }
            else if(arr[i][j] < low) {
                lowpos = j;
                low=arr[i][j];
            }
    std::cout << "\nBiggest element:" <<high<< "\nSmallest:" << low << "\n";
    return {highpos, lowpos};
}
void rows_swap(Arr table2d, int nrow = rows){
    auto p = high_low_ids(table2d);
    const int high_idx = p.first;
    const int low_idx = p.second;
    if (high_idx == low_idx)
        return;
    for (int i = 0; i < nrow; ++i) {
        std::swap(table2d[i][high_idx], table2d[i][low_idx]);
    }
}
void print_arr(Arr arr, int nrow = rows, int ncol = cols) {
    for (int i = 0; i < nrow; i++) {
        for (int j = 0; j < ncol; j++)
            std::cout << std::left << std::setw(6) << arr[i][j];
        std::cout << std::endl;
    }
}
int main () {
    srand(time(0));
    Arr arr;
    for (int i = 0; i < rows; ++i)
        for (int j=0; j<cols; ++j)
            arr[i][j] = 1 + (rand() % 200); 
    std::cout << "Random 2d generated array:\n";
    print_arr(arr);
    rows_swap(arr);
    std::cout << "Swapped array:\n";
    print_arr(arr);
    return 0;
}

PS. please avoid using namespace std.

Upvotes: 2

Related Questions