3

I am beginner in programming, and I have a problem. I have to create two dimensional array [5][3] ... Lets says this is example of part of this:

  1. 2 3 4
  2. 7 8 9
  3. 5 6 7

Then I have to get sum of lines and write it next to this :

  1. 2 3 4 9
  2. 7 8 9 24
  3. 5 6 7 18

Now, I have to sort arrays by this sum, so the result would look like this:

  1. 7 8 9 24
  2. 5 6 7 18
  3. 2 3 4 9

I dont know how to achieve this, this is my code:

    #include <iostream>
    #include <time.h>
    using namespace std;


    void tocke(int polje[5][3])
    {
      int vsota;
       srand(time(NULL));
       int sums[5];
for (int i = 0; i < 5; i++)
{
    vsota = 0;
    cout << endl;
    cout << i + 1 << ". ";

    for (int j = 0; j < 3; j++){
        polje[i][j] = (rand() % 10 + 1);
        vsota += polje[i][j];
        sums[i] = vsota;
        cout << polje[i][j] << "  ";
    }
}   
    }

    void urejaj(int polje[5][3])
    {
cout << "\n\n\n\n" << endl;
int sums[5];
int vsota ;
double temp;




for (int i = 0; i < 5; i++)
{
    vsota = 0;
    cout << endl;
    cout << i + 1 << ". ";
    for (int j = 0; j < 3; j++)
    {

        vsota += polje[i][j];
        sums[i] = vsota;

        if (sums[i] < sums[i+1])
        {

            temp = polje[i][j];
            polje[i][j] = polje[i + 1][j];
            polje[i + 1][j] = temp;

        }

        cout << polje[i][j] << " ";

    }cout << sums[i];

    }

    }











   int main()
    {
int polje[5][3];
tocke(polje);
urejaj(polje);
cout << "\n";
system("pause");
return 0;


   }

First function writes elements in field, and the second has to sort fields.

2
  • After sumation, try copying the arrays to new array but with proper order. Commented Nov 21, 2013 at 19:59
  • You could make a function which compares two multi-dimensional arrays and then compare the first two and then compare the result of the first two with the third one? Commented Nov 21, 2013 at 20:22

4 Answers 4

6

Your issue may be easier resolved by changing your data structures. Instead of having an array of arrays, have an array of structures. The structure would contain the sum and the array of values.

struct Row
{
  int sum;
  std::vector<int> values;
};

Row data[5];

With this concept, you are sorting the rows by their sums.
You can easily write a comparator for this and use std::sort:

bool Compare_Rows(const Row& a, const Row &b)
{
  return a.sum < b.sum;
}

//...
std::sort(&data[0], &data[5], Compare_Rows);

Edit 1 -- Overloading operator <
You could simplify and not require a comparator by providing an overloaded operator <:

struct Row
{
  int sum;
  std::vector<int> values;

  bool operator<(const Row& other)
  {
    return sum < other.sum;
  }
};

The sorting call now becomes:

std::sort(&data[0], &data[5]);
Sign up to request clarification or add additional context in comments.

5 Comments

"OOPs" did it again ;) +1. Instead of Compare_Rows, can we have an overloaded `operator< ?
sum is never assigned, is it?
@BrianGradin: The member sum is left for the O.P. to calculate. The values member should also be filled in by the O.P.
Use non-member begin and end on built in arrays instead. Using std::sort(std::begin(data), std::end(data)), the parameters get more generic and it is possible to change container at a later stage without changing this code.
This is very helpful, but it has to be more similar to my code, beacuse its for school, and the rules for exercise are, that it has to have two functions, as I wrote in my code :) thank you anyway
3

In case you're still lost, here's the full program:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
using namespace std;

void display_matrix(int**, int, int);
void gen_matrix(int**, int, int);
void gen_matrix_sum(int**, int**, int, int);
void sort_matrix(int**, int**, int, int);

int main()
{
    srand(time(0));
    int m=5, n=3;

    int** my_matrix = (int**)malloc(m*sizeof(int*));
    for (int i=0; i<m; i++) my_matrix[i] = (int*)malloc(n*sizeof(int));
    gen_matrix(my_matrix, m, n);
    display_matrix(my_matrix, m, n);
    cout << endl;

    int** my_matrix_sum = (int**)malloc(m*sizeof(int*));
    for (int i=0; i<m; i++) my_matrix_sum[i] = (int*)malloc((n+1)*sizeof(int));
    gen_matrix_sum(my_matrix_sum, my_matrix, m, n);
    display_matrix(my_matrix_sum, m, n+1);
    cout << endl;

    int** my_matrix_sorted = (int**)malloc(m*sizeof(int*));
    for (int i=0; i<m; i++) my_matrix_sorted[i] = (int*)malloc((n+1)*sizeof(int));
    sort_matrix(my_matrix_sorted, my_matrix_sum, m, n);
    display_matrix(my_matrix_sorted, m, n+1);   
    cout << endl;
}

void display_matrix(int** my_matrix, int m, int n)
{
    for (int i=0; i<m; i++)
    {
        for (int j=0; j<n; j++)
            cout << setw(2) << my_matrix[i][j] << " ";
        cout << endl;
    }
}

void gen_matrix(int** M, int m, int n)
{
    int random_limit = 10;

    for (int i=0; i<m; i++)
        for (int j=0; j<n; j++)
            M[i][j] = rand()%random_limit + 1;
}

void gen_matrix_sum(int** M, int** my_matrix, int m, int n)
{
    int aux[m];

    for (int i=0; i<m; i++)
        aux[i] = 0;

    for (int i=0; i<m; i++)
        for (int j=0; j<n; j++)
        {
            M[i][j] = my_matrix[i][j];
            aux[i] += M[i][j];
        }

    for (int i=0; i<m; i++)
        M[i][n] = aux[i];   
}

void sort_matrix(int** my_matrix_sorted, int** my_matrix, int m, int n)
{
    int v_sum_values[m];

    for (int i=0; i<m; i++)
        v_sum_values[i] = my_matrix[i][n];

    int v[n];   
    int max = v_sum_values[0];
    int index;
    for (int i=0; i<m; i++)
    {

        for (int j=0; j<m; j++)
        {
            if (v_sum_values[j]>max)
            {
                max = v_sum_values[j];
                index = j;
            }
        }
        v_sum_values[index] = -1;
        v[i] = index;   
        max = v_sum_values[i];
    }

    for (int i=0; i<m; i++)
        for (int j=0; j<n+1; j++)
            my_matrix_sorted[i][j] = my_matrix[v[i]][j]; 
}

1 Comment

This is very helpful, but it has to be more similar to my code, beacuse its for school, and the rules for exercise are, that it has to have two functions, as I wrote in my code :) thank you anyway
0

Here's how I would approach the problem:

Write a swap function which switches two rows in a multidimensional array. Something like:

// columns is the number of columns; ie array[rows][columns]
void swap(int[][] array, const int columns, int switch1, int switch2)
{
    for (int i = 0; i < columns; i++)
        array[switch1][i] ^= array[switch2][i] ^= array[switch1][i] ^ array[switch2][i];
}

Then, write a sum function, which adds all elements in a row. Something like:

int sumCol(int[][] array, int columns, int index)
{
    int sum = 0;
    for (int i = 0; i < columns; i++)
        sum += array[index][i];
    return sum;
}

Finally, write a sort function which is able to sort a multidimensional array using the following operations:

  • Comparing the sum of two rows
  • Swapping two rows

I'll leave it up to your preference to decide which sorting algorithm to use.

Comments

0

I have to create two dimensional array

I don't know what you mean by this (do you have to read it from some input, or populate it with numbers etc. ?), but lets say you create a two dimensional matrix like this:

// Just a type alias for the matrix.
template <typename T, std::size_t R, std::size_t C>
using Matrix = std::array<std::array<T, C>, R>;

// Create two dimensional matrix [3][3] of ints.
Matrix<int, 3, 3> matrix = {{ { 2, 3, 4 },
                              { 7, 8, 9 },
                              { 5, 6, 7 } }};

Then you can sort the matrix by the sum of each row in descending order like in the following example. I have used std::sort together with a custom comparator functor (created with a lambda function):

std::sort(std::begin(matrix), std::end(matrix), [] (decltype(*matrix.cbegin())& lhs, decltype(*matrix.cbegin())& rhs) {
    return std::accumulate(std::begin(lhs), std::end(lhs), 0) > std::accumulate(std::begin(rhs), std::end(rhs), 0);
});

That's it.

Now let's output the matrix:

for (decltype(matrix.size()) row = 0; row != matrix.size(); ++row) {
    std::cout << row + 1 << ". ";
    for (const auto i : matrix[row]) {
        std::cout << i << " ";
    }
    std::cout << std::accumulate(std::begin(matrix[row]), std::end(matrix[row]), 0);
    std::cout << std::endl;
}

Live example

1 Comment

This is very helpful, but it has to be more similar to my code, beacuse its for school, and the rules for exercise are, that it has to have two functions, as I wrote in my code :) thank you anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.