0

I 've to do the following exercise:

Write a function that given two integers (x and k ) and a M X N matrix, returns TRUE if there is an element that occurs at least k times in at least x columns of the matrix.

this is my solution but there is something wrong:

#include <iostream>
using namespace std;

const int DIM = 3;

bool check ( int matrix[DIM][DIM], int element,  int k,  int x )
{
    bool occur = false;
    int i,j = 0;
    for ( i=0; i<DIM; i++ )
    {
        for ( j=0; j<DIM; j++)
        {
            while ( i<k && occur)
            {
                matrix[i][j] == element;
                i++;
            }
        }
    }
    return occur;
}

int main ()
{
    int matrix[DIM][DIM] = {{1,2,3},
                            {4,1,6},
                            {7,8,9}};
    int x = 2;
    int k = 1;
    int elemento = 1;
    if ( check (matrix, element, k , x))
    {
        cout << "l'elemento "<< elemento <<" ricorre "<< k <<" volta/e in "<< x <<" colonna/e";
    }
    return 0;
}
5
  • 3
    What is wrong? What's happening? What's not happening? Commented Apr 22, 2012 at 13:31
  • 1
    You never set occur. You need to sit and think about your algorithm. Commented Apr 22, 2012 at 13:33
  • 1
    For an error description like "something is wrong", our solution can't be much more than "fix something" :-) If you want more, first of all give all relevant information to describe your problem as precisely as you can. Commented Apr 22, 2012 at 13:35
  • agree with mert, there's never occur = true Commented Apr 22, 2012 at 13:36
  • i < k and matrix[i][j] == element; seems incorrect. Also what mert said. Commented Apr 22, 2012 at 13:49

2 Answers 2

1

You need to separate the task into smaller chunks. To check if a number occurs k times in x columns, first write a function to check if a number occurs k times in one column. That function will have a single for loop. When you write it, test it to see if you did it correctly. Then put that function in another, very similar for loop and you're done.

Sign up to request clarification or add additional context in comments.

Comments

0
bool check(int matrix[M][N], int element, int k, int x)
{
        int c1 = 0;
        for (int i = 0; i < M; ++i) {
                int c2 = 0;
                for (int j = 0; j < N; ++j) {
                        if (matrix[i][j] == element)
                                ++c2;
                }
                if (c2 >= k)
                        ++c1;
        }
        return c1 >= x;
}

Optimize it yourself ;)

Comments

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.