Vector inside the matrix?

Asked

Viewed 47 times

0

My function needs to find the line where the first occurrence of a vector occurs within a matrix and return its line. But it is always returning the wrong line, my logic is wrong?

My job:

int busca( int mat[][MAX],int n, int m, int N, float vetor[])
{  
int i,j,k,aux;

for(k=0;k<N;k++)
{
    printf("Informe o valor do %d vetor:", k+1  ); // le o vetor
    scanf("%f",&vetor[k]);
}

for (i =0; i < n ;i ++)
{
    for ( j = 0; j < m ;j ++)
    {
        printf ("Digite mat [%d][%d]: ",i , j) ; //le a matriz
        scanf ("%d",&mat [i][j]) ;
    }
}

//aqui seria a logica pra achar o elemento igual
for(i=0; i<n;i++)
{
    for(j=0;j<m;j++)
    {
        if(mat[i][j] == vetor[k])
        {
            return i;

        }
    }
}

if (i>=0)  
printf("  A primeira ocorrencia do vetor eh na linha %d\n.",i-1 );
else
return -1;
}

2 answers

1


Your logic for finding the vector is incomplete, because you need to reset the variable k, which was previously used in that part of the code:

for(k=0;k<N;k++)
{
    printf("Informe o valor do %d vetor:", k+1  ); // le o vetor
    scanf("%f",&vetor[k]);
}

Then one solution, using its logic still, would be the following:

// essa variável deve ser utilizada antes da repetição
int cont;

///aqui seria a logica pra achar o elemento igual
for(i=0; i<n;i++)
{
    cont=0;
    k = 0;

    for(j=0;j<m;j++, k++)
    {
        //essa condição serve para caso o "k" ultrapasse o tamanho
        // "N" do vetor, evitando acessar um índice do vetor que
        // não existe
        if(k>=N)
        {
            k=0;
        }

        if(mat[i][j] == vetor[k])
        {
            // aqui a variável conta quantos elementos do vetor 
            // são iguais a linha "i" da matriz
            cont++; 
        }
    }

    // se "cont" for igual a quantidade "N" de elementos do vetor
    // isso quer dizer que o programa encontrou a primeira ocorrência
    // do vetor na matriz 
    if(cont == N)
    {
        break;
    }
}

The output display should also be corrected to the following:

    if (i>=0 && cont == N) 
        // Tem que ser utilizado "i" e não "i-1", pois caso o "i"
        // seja igual a zero, será exibido -1
        printf("  A primeira ocorrencia do vetor eh na linha %d\n.",i );
    else
        return -1;

I hope I’ve helped.

0

Your logic is wrong. I have not tested the code but what its function does is to return the first line containing the last element of the vector. A good alternative would be to do the following:

//aqui seria a logica pra achar o elemento igual
for(i == 0; i < n; i++){
    if(!memcmp(mat[n], vector, sizeof(vector));
        return i;
}

return -1

The function memcmp compares two code blocks and returns 0 if the blocks are equal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.