How to swap 2d array columns in places? - c++

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";
}

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.

Related

I am not sure why this vector transpose is not working

I want to tranpose a matrix using vector?
//I am trying to 'tranpose' a vector matrix, but it's not running
#include <iostream>
#include <vector>
using namespace std;
// this will tranpose matrix
int transpose(vector<vector<int>> &arr){
int n = arr.size();
int m = arr[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}}}
// this will swap the matrix
int swap_vector(vector<vector<int>> &arr){
int n = arr.size();
int m = arr[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m/2; j++) {
int temp = arr[i][j];
arr[i][j] = arr[i][j-1-i];
arr[i][j-1-i] = temp;
}}}
vector<vector<int>> arrh{{1,2,3,4},{5,6,7,8},
{9,10,11,12},
{13,14,15,16} };
int main() {
transpose(arrh);
swap_vector(arrh);
for (int i=0; i<arrh.size(); i++) {
for (int j=0; j<arrh[0].size(); j++) {
cout << arrh[i][j] << " ";}
cout << std::endl;}
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
// this will tranpose matrix
int transpose(vector<vector<int>> &arr){
int n = arr.size();
int m = arr[0].size();
for (int i = 0; i < n; i++) {
for (int j = i; j < m; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
// this will swap the matrix
int swap_vector(vector<vector<int>> &arr){
int n = arr.size();
int m = arr[0].size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m/2; j++) {
int temp = arr[i][j];
arr[i][j] = arr[i][m-1-j];
arr[i][m-1-j] = temp;
}
}
}
vector<vector<int>> arrh{{1,2,3,4},{5,6,7,8},
{9,10,11,12},
{13,14,15,16} };
int main() {
transpose(arrh);
swap_vector(arrh);
for (int i=0; i<arrh.size(); i++) {
for (int j=0; j<arrh[0].size(); j++) {
cout << arrh[i][j] << " ";
}
cout << std::endl;
}
return 0;
}

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.

Add the Edges of 2D array and return its answer

What's wrong with my code
I Have to add all the edge values of the 2D Array.
The Function is not returning what I want. Its returning garbage value.
Program Req Output : Add all the edges value of the 2D Array and return its answer.
You are not allowed to use Vector etc.
Here is my Code :
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
int k = 0;
int l = 0;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= cols; j++)
{
if (i == 1 || i == rows || j == 1 || j == cols)
{
sum = arr[k][l];
totalOfEdges = sum + totalOfEdges;
}
l++;
}
k++;
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
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] << " ";
}
cout << endl;
}
AddEdges(arr);
}
My Output :
Leaving the Correct Code in Case Any one need it .
#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 4;
void AddEdges (int arr[rows][cols])
{
int sum = 0;
int totalOfEdges = 0;
int i,j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
if (i == 0 || i == (rows-1) || j == 0 || j == (cols-1))
{
sum = arr[i][j];
totalOfEdges = sum + totalOfEdges;
}
}
}
cout << "Total of Edges = " << totalOfEdges << endl;
}
int main()
{
int arr[3][4] = {0};
cout << "Enter Elements for Array = \n";
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cin >> arr[i][j];
}
}
cout << "--------" << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
AddEdges(arr);
}

C++: push_back() function doesn't append double values: segmentation core dumped

I am having trouble with the push_back() function in C++. For a reason which I don't understand, the push_back function will "not accept" the value I am telling it to append, but the code works perfectly until I try to display the values I want (end of code). I have checked the value type, which is double, but it still won't append it.
The value I am trying to insert comes from a function which calculates the mean of a vector, taking out the NaN values. The code works perfectly but when I am trying to display the values I want, I always get: Segmentation fault (core dumped).
This mean function first iterates over a range and creates a vector in which the NaN will be taken away. Then the mean will be calculated. I have spent quite some time on trying to figure out where the error could come from but wasn't able to figure out anything so any help would be highly appreciated. The following mean function:
double mean_func(double **arr, int iterations, int header, int start){
std::vector<double> vec;
for (int i=start-iterations; i < start; i++){
vec.push_back(arr[i][header]);
}
vec.erase(std::remove_if(std::begin(vec),
std::end(vec),
[](const auto& value) { return std::isnan(value); }),
std::end(vec));
double sum = std::accumulate(vec.begin(), vec.end(), 0.0);
double mean = sum / vec.size();
return mean;
}
The whole code where transf_array_2_vec transforms a vector to an array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <typeinfo>
double** transf_vec_2_array(std::vector<std::vector<double> > vals, int N, int M)
{
double** temp;
temp = new double*[N];
#pragma omp parallel for
for(int i=0; (i < N); i++)
{
temp[i] = new double[M];
for(int j=0; j < M; j++)
{
temp[i][j] = vals[i][j];
}
}
return temp;
}
double mean_func(double **arr, int iterations, int header, int start){
std::vector<double> vec;
for (int i=start-iterations; i < start; i++){
vec.push_back(arr[i][header]);
}
vec.erase(std::remove_if(std::begin(vec),
std::end(vec),
[](const auto& value) { return std::isnan(value); }),
std::end(vec));
double sum = std::accumulate(vec.begin(), vec.end(), 0.0);
double mean = sum / vec.size();
return mean;
}
double** cfun(double **indata, unsigned int rows, unsigned int cols, int max_inputs, int daily_inputs, int weekly_inputs, int inputs_short_term, const char **header_1, const char **header_2, unsigned int size_header_1, unsigned int size_header_2, double **outdata) {
std::vector< std::vector <double>> seq_collec;
std::vector<double>seq;
unsigned int i, j, k, l;
unsigned int temp= 5080;
int num = omp_get_thread_num();
omp_set_num_threads(num);
//#pragma omp parallel for //private(seq)
for(i = max_inputs + weekly_inputs; i < temp ; i++) {
for(j = 0; j < size_header_1; j++ ){
for(k = 0; k < size_header_2 ; k++){
for(l = i-max_inputs; l < i; l++){
if((strcmp(header_2[k],"price")==0)|| (strcmp(header_2[k], "change")==0)){
seq.push_back(indata[l][j+k]);
seq.push_back(mean_func(indata, inputs_short_term, j*size_header_2, l));
//std::cout << i << " " << j << " " << k <<std::endl;
//std::cout << header_1[j] << " " << header_2[k] << std::endl;
//std::cout << typeid(mean).name() << std::endl;
//std::cout << mean_func(indata, inputs_short_term, j*size_header_2, l) << std::endl;
}else{
seq.push_back(indata[l][j+k]);
//std::cout << header_1[k] << " " << header_2[k] << std::endl;
}
}
}
seq.push_back(mean_func(indata, daily_inputs, j+k, l));
seq.push_back(mean_func(indata, weekly_inputs, j+k, l));
}
//std::cout << seq.size() << std::endl;
seq_collec.push_back(seq);
seq.clear();
}
outdata = transf_vec_2_array(seq_collec, seq_collec.size(), seq_collec[0].size());
//std::cout << seq_collec.size() << std::endl;
//std::cout << seq_collec[0].size() << std::endl;
return outdata;
}
int main(){
int rows = 10846, cols = 12, max_inputs = 20, daily_inputs = 1000, weekly_inputs=5000, inputs_short_term=4;
unsigned int size_header_1 = 3, size_header_2 = 4;
const char *header_1[size_header_1] = {"CH:SMI","DJIA","RUI"};
const char *header_2[size_header_2] = {"change","delta_vol","price","volume"};
double* *indata = new double*[rows];
double* *outdata = new double*[rows];
for (int i=0; i < rows; i++){
indata[i] = new double[cols];
outdata[i] = new double[cols];
}
for (int i=0; i < rows; i++){
for (int j=0; j < cols; j++){
indata[i][j]=i + j ;
}
}
outdata = cfun(indata, rows, cols, max_inputs, daily_inputs, weekly_inputs, inputs_short_term, header_1, header_2, size_header_1, size_header_2, outdata);
for(int j = 0; j < 1; j++){
for(int i = 0; i < 366; i++){
std::cout << outdata[i][j] << std::endl; // PROBLEM HERE !!!
}
}
return 0;
}

2D (Maximum From Each Column)

After trying a lot of times and thinking again and again.. It feels like a frustrated person.
I'm here to get some suggestions from you guys..
Actually I'm trying to find the maximum of each ROW and COLUMN.
So by using divide and conquer technique, I write two separate functions one for finding max of each row and store it to row vector that i used as an argument. Respectively for columns.
void maxValuesR(int a[][cols], int rv[], int row)
void maxValuesC(int a[][cols], int cv[], int row)
PROBLEM: The code is not even compile, I just don't understnd the errors..
Please Help..
I Really Need Your Help Here!
The code is as follow:
#include <iostream>
using namespace std;
const int rows = 2; // Declared As Global Variable
const int cols = 3; // Declared As Global Variable
void getData(int arr[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << "Enter Element: ";
cin >> arr[i][j];
}
}
}
void printData(int a[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
cout << a[i][j] << "\t";
}
cout << endl;
}
}
void print_single(int a[], int row)
{
for(int i = 0; i < row; i++)
{
cout << a[i] << "\t";
}
}
void maxValuesR(int a[][cols], int rv[], int row)
{ int foxi;
for(int i = 0; i < row; i++)
{
foxi = a[i][0];
for(int j = 0; j < cols; j++)
{
if(foxi < a[i][j])
{
foxi = a[i][j];
}
}
rv[i] = foxi;
}
}
void maxValuesC(int a[][cols], int cv[], int row)
{
int maxi;
for(int i = 0; i < cols; i++)
{
maxi = a[0][i];
for(int j = 0; j < row; j++)
{
if(maxi > a[j][i])
{
maxi = a[j][[i];// show error here => expected a '{' introducing lambda body
}
}
cv[i] = maxi;
}
}
int main()
{
int rowVector[rows];
int colVector[cols];
int a[rows][cols];
cout << "Fill Array_1. " << endl;
getData(a, rows);
cout << "Array_1." << "\n\n";
printData(a, rows); cout << endl;
maxValuesR(a, rowVector, rows);
print_single(rowVector, rows);
cout << "\n\n";
maxValuesC(a, colVector, rows);
print_single(colVector, rows);
return 0;
}
To clarify the compile errors:
You forgot the include (or didn't write it here?) #include <iostream>
You didn't specify the namespace for cin, cout and endl (they are in std namespace)
You had a superfluous "[" in the statement a[j][[i], by all likelihood you wanted to write a[j][i]
The compiling code looks like this:
#include <iostream>
const int rows = 2; // Declared As Global Variable
const int cols = 3; // Declared As Global Variable
void getData(int arr[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
std::cout << "Enter Element: ";
std::cin >> arr[i][j];
}
}
}
void printData(int a[][cols], int rows)
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
std::cout << a[i][j] << "\t";
}
std::cout << std::endl;
}
}
void print_single(int a[], int row)
{
for(int i = 0; i < row; i++)
{
std::cout << a[i] << "\t";
}
}
void maxValuesR(int a[][cols], int rv[], int row)
{ int foxi;
for(int i = 0; i < row; i++)
{
foxi = a[i][0];
for(int j = 0; j < cols; j++)
{
if(foxi < a[i][j])
{
foxi = a[i][j];
}
}
rv[i] = foxi;
}
}
void maxValuesC(int a[][cols], int cv[], int row)
{
int maxi;
for(int i = 0; i < cols; i++)
{
maxi = a[0][i];
for(int j = 0; j < row; j++)
{
if(maxi > a[j][i])
{
maxi = a[j][i];
}
}
cv[i] = maxi;
}
}
int main()
{
int rowVector[rows];
int colVector[cols];
int a[rows][cols];
std::cout << "Fill Array_1. " << std::endl;
getData(a, rows);
std::cout << "Array_1." << "\n\n";
printData(a, rows);
std::cout << std::endl;
maxValuesR(a, rowVector, rows);
print_single(rowVector, rows);
std::cout << "\n\n";
maxValuesC(a, colVector, rows);
print_single(colVector, rows);
return 0;
}
Can't tell whether it produces the output you want, though, because you didn't specify any example input (let alone the corresponding expected output)...