Ir ao conteúdo

Posts recomendados

Postado

1   Uma imagem em preto e branco, de tamanho m x n, pode ser representada por uma matriz cujos elementos assumem valores no conjunto {0,1}. Dado um padrão representado por uma matriz 33 também assumindo valores em {0,1}, escreva uma função, ou trecho de código, que determine se o padrão existe ou não na imagem.

(8 pontos)

<code>

using System;

using System.IO;




namespace Testes

{

            class Program

            {

                        static void Main(string[] args)

                        {

                                    CriaMatriz("A.txt", 200, 350);

                                    CriaMatriz("B.txt", 3, 4);




                                    int[,] A = LerMatriz("A.txt");

                                    int[,] B = LerMatriz("B.txt");




                                    Console.WriteLine(NumeroDeOcorrencias(A, B));

                        }




                        static int NumeroDeOcorrencias(int[,] matriz, int[,] padrão)

                        {

                                    int N = matriz.GetLength(0), M = matriz.GetLength(1);

                                    int n = padrão.GetLength(0), m = padrão.GetLength(1);

                                    int contador = 0;

                                   

                                    ///////////////////////////////////////////////////////

                                    //

                                    //  Escreva seu código aqui

                                    //

                                    ///////////////////////////////////////////////////////

                                   

                                    return contador;

                        }




                        static int[,] LerMatriz(string fileName)

                        {

                                    FileStream f = new FileStream(fileName, FileMode.Open);

                                    StreamReader sr = new StreamReader(f);

                                    string[] tamanho = sr.ReadLine().Split(' ');

                                    int n = int.Parse(tamanho[0]);

                                    int m = int.Parse(tamanho[1]);

                                    int[,] ret = new int[n,m];

                                    for(int i=0; i<n; ++i)

                                    {

                                               string linha = sr.ReadLine();

                                               for (int j = 0; j < m; ++j)

                                                           ret[i, j] = linha[j] == '0' ? 0 : 1;

                                    }

                                    sr.Close();

                                    return ret;

                        }




                        static void CriaMatriz(string fileName, int n, int m)

                        {

                                    Random r = new Random();

                                    FileStream f = new FileStream(fileName, FileMode.Create);

                                    StreamWriter sw = new StreamWriter(f);

                                    sw.Write($"{n} {m}\r\n");

                                    for (int i = 0; i < n; ++i)

                                    {

                                               for (int j = 0; j < m; ++j)

                                                           sw.Write(r.Next(2) == 0 ? '0' : '1');

                                               sw.Write("\r\n");

                                    }

                                    sw.Close();

                                    f.Close();

                        }

            }

}

</code>

 

teste.PNG

  • Obrigado 1
  • 2 semanas depois...
Postado

@ivanRezende      uma maneira de testar esse padrão é criar um mapa das posições da matriz , e ao encontrar um padrão insira nesse mapa o padrão  assim ao comparar o restante da Matriz  saberá se está sobrepondo um outro já encontrado antes ,  e usando essas duas matrizes do exemplo que você postou , ou com geradas matrizes aleatóriamente , seu código poderia ser assim  :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Globalization;
using System.Threading.Tasks;
using System.Runtime.ConstrainedExecution;
using System.Xml.Schema;
namespace matriz_121
{
    internal class Program
    {
        static void Main(string[] args)
        {   /// CriaMatriz("A.txt", 200, 350);                           
            /// CriaMatriz("B.txt", 3, 4);
            ///                Matriz principaL   Matriz padrão
            ///  usando o exemplo  001010100         101
            ///                    101010110         011
            ///                    110110110         101
            ///                    001010000
            int[,] A = LerMatriz("A.txt");  
            int[,] B = LerMatriz("B.txt");                  
            int[,] aux = new int[200, 350];
            Console.WriteLine("\nQtd de OcorrenciaS = " + NumeroDeOcorrencias(A, B, aux));
            Console.BackgroundColor = (ConsoleColor)((4) % 16);
            Console.WriteLine("                                   ");
            Console.BackgroundColor = (ConsoleColor)((0) % 16);
            ///grafico(aux);
        }
        static int NumeroDeOcorrencias(int[,] matriz, int[,] padrão, int[,] aux)
        {
            int N = matriz.GetLength(0), M = matriz.GetLength(1);
            int n = padrão.GetLength(0), m = padrão.GetLength(1);
            for (int w = 0; w < N; w++) for (int k = 0; k < M; k++)
                    aux[w, k] = 7; /// preench a matriz Aux , usada como um mapa , com valor 7
            int contador = 0;
            int elemento = 0;
            int i = 0, j = 0;
            for (i = 0; i < N - (n - 1); ++i)      /// percore todas as linhas da Mat Principal 
            {                                      /// menos a qtd da matriz padrão
                for (j = 0; j < M - (m - 1); ++j)  /// percore todas as colunas da Mat principal
                {                                  /// menos a qtd da matriz padrão
                    elemento = 0;                  /// inform a qtd de posições iguais nas duas
                    for (int w = 0; w < n; w++)    /// percore todas as linhas da Mat Principal 
                    {
                        for (int k = 0; k < m; k++)/// percore todas as colunas da Mat Principal 
                        {
                            if (matriz[i + w, j + k] == padrão[w, k] &&
                                aux[i + w, j + k] == 7) /// verif as pos das duas Matr e no mapa
                                elemento += 1;
                        }
                    }
                    if (elemento == (n * m))       /// qtd element iguais entre as duas matrizes
                    {                              /// Eh igual total elementos da Matr padrão ?
                                                   /// String.Format("{0,10:0.0}", contador/*123.4567*/); "     123.5"
                        contador += 1;             /// incrementa a qtd de Ocorrencias
                        string valor = contador.ToString("D3"); /// formatar a saIda p ficar na mesmo coluna
                        Console.WriteLine("achou " + valor + " iguais");
                        for (int w = 0; w < n; w++)
                            for (int k = 0; k < m; k++)
                                aux[i + w, j + k] = matriz[i + w, j + k];/// coloca no mapa a matriz padrão
                                                                         /// pois essas pos não pode ser mais usadas
                    }
                }
            }
            Console.WriteLine("\nMatriz Aux é Mapa e onde padrão Se encaixA\n");
            for (i = 0; i < N; ++i)           /// percore todas as linhas da Mat Auxiliar 
            {
                for (j = 0; j < M; ++j)       /// percore todas as colunas da Mat Auxiliar
                {
                    Console.BackgroundColor = (ConsoleColor)((0) % 16);
                    if (aux[i, j] == matriz[i, j])
                    {
                        Console.BackgroundColor = (ConsoleColor)((4) % 16);
                        Console.Write(aux[i, j]); /// escreve a matr aux
                    }
                    else
                    {
                        Console.Write(matriz[i, j]); /// escreve a matr matriz
                    }
                }
                Console.WriteLine();
            }
             Console.Beep(4096, 100);
            Thread.Sleep(300);
             return contador;
        }
        static int[,] LerMatriz(string fileName)
        {
            FileStream f = new FileStream(fileName, FileMode.Open);
            StreamReader sr = new StreamReader(f);
            string[] tamanho = sr.ReadLine().Split(' ');
            int n = int.Parse(tamanho[0]);
            int m = int.Parse(tamanho[1]);
            int[,] ret = new int[n, m];
            for (int i = 0; i < n; ++i)
            {
                string linha = sr.ReadLine();
                for (int j = 0; j < m; ++j)
                {
                    ret[i, j] = linha[j] == '0' ? 0 : 1;
                }
            }
            sr.Close();
            return ret;
        }
        static void CriaMatriz(string fileName, int n, int m)
        {
            Random r = new Random();
            FileStream f = new FileStream(fileName, FileMode.Create);// abre o arquivo nomeado fileName
            StreamWriter sw = new StreamWriter(f);                   // escritor do arquivo
            sw.Write($"{n} {m}\r\n");
            for (int i = 0; i < n; ++i)
            {
                for (int j = 0; j < m; ++j)
                {
                    sw.Write(r.Next(2) == 0 ? '0' : '1');
                }
                sw.Write("\r\n");
            }
            sw.Close();
            f.Close();
        }
        /********    
                *    
                static int[,] grafico(int[,] aux )
                {
                    int N = aux.GetLength(0), M = aux.GetLength(1);
                    for (int i = 0; i < N; ++i)
                    {
                        for (int j = 0; j < M; ++j)
                        {
                            if (aux[i,j] == 1) 
                            {
                                Console.Beep(1,1);                    /// emite um bip no speker do sistema
                                Console.SetPixel(i,j,RGB(255,255,0)); /// desenhar a matriz na tela
                                                                      /// Cor amarela
                             }
                         }
                    }
                }
                *
        *********/
    }
}

 

  • Curtir 1

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

LANÇAMENTO!

eletronica2025-popup.jpg


CLIQUE AQUI E BAIXE AGORA MESMO!