Upload
ngokhanh
View
247
Download
0
Embed Size (px)
Citation preview
Nelson Freire (ISEP–DEI-APROG 2012/13) 1/28
Matrizes Algoritmia e Java
APROG Algoritmia e Programação
Nelson Freire (ISEP–DEI-APROG 2012/13) 2/28
Enquadramento
Noção
Interesse
Uso
Declaração
Java: Matriz é um Array de Arrays
Manipulação de Elementos
Transferência entre Módulos/Métodos
Passagem de Parâmetros
Retorno da Função
Exemplo
Matrizes Sumário
Exemplos
Soma
Global
Cada Linha
Cada Coluna
Diagonal Principal
Maior
Global
Cada Linha
Cada Coluna
Matriz
Transposta
Ordenada
Nelson Freire (ISEP–DEI-APROG 2012/13) 3/28
12 15 10 18 ... 13 14
elemento 2 valor 10
comprimento (ou dimensão) n
elementos
índices
Tipos de Arrays
Vetor // array uni-dimensional
Matriz // array bi-dimensional
Vector
Estrutura de dados complexa
Armazena múltiplos valores ao mesmo tempo
Valores
Todos do mesmo tipo
Organizados de forma linear
Dimensão
Fixa
Não pode ser alterada em tempo de execução (run-time)
0 1 2 3 ... n-2
n-1
Matrizes Enquadramento
Nelson Freire (ISEP–DEI-APROG 2012/13) 4/28
Estrutura de dados complexa
Armazena múltiplos valores ao mesmo tempo
Valores
Todos do mesmo tipo
Organizados em linhas e colunas
Dimensão
Fixa
Não pode ser alterada em tempo de execução (run-time)
0 1 ... m-1
0 11 24 ... 27
1 5 56 ... 18
... ... ... ... ...
n-1 1 8 ... 34
índice de coluna (comprimento m)
índice de linha (comprimento n)
elemento (1,m-1) valor 18
dimensão n x m
Matrizes Noção de Matriz
Nelson Freire (ISEP–DEI-APROG 2012/13) 5/28
Armazenar
Tabelas bidimensionais
Valores
Todos do mesmo tipo
Organizados em linhas e colunas
Exemplos
Tabela de notas de alunos // conjunto de números inteiros organizados em linhas e colunas
Tabela de disciplinas de um curso // conjunto de Strings organizadas em linhas e colunas
Matrizes Interesse
Nº Aluno Português Inglês Matemática
1138 12 15 19
1249 18 17 12
1544 15 12 14
Ano Disciplinas
1º APROG LAPR1 PRCMP PPROG ESOFT LAPR2
2º ARQCP BDDAD ESINF EAPLI LAPR3 LAPR4
3º ASIST ALGAV ARQSI SGRAI LAPR5 PESTI
Nelson Freire (ISEP–DEI-APROG 2012/13) 6/28
Preciso Saber
Declarar uma matriz
Java
Matriz é um Array de Arrays
Manipular elementos de uma matriz
Transferir uma matriz entre módulos/métodos
Matrizes Uso
Nelson Freire (ISEP–DEI-APROG 2012/13) 7/28
Algoritmia
Declaração 1: dimensão definida na declaração
Sintaxe: tipo nomeMatriz[Linhas][Colunas]
Ex: INTEIRO notas[20][10]
Declaração 2: dimensão definida depois da declaracão
Sintaxe: tipo nomeMatriz[ ][ ] ...
criar nomeMatriz[Linhas][Colunas]
Ex: INTEIRO notas[ ][ ]
criar notas[20][10]
Java
tipo nomeMat[ ][ ] = new tipo [Linhas][Colunas];
int notas[ ][ ] = new int[20][10];
ou tipo[ ][ ] nomeMat = new tipo [Linhas][Colunas];
int[ ][ ] notas = new int[20][10];
tipo nomeMatriz[ ][ ]; ...
nomeMat= new tipo [Linhas][Colunas];
int notas[ ][ ];
notas = new int[20][10];
RAM
notas[0,0]
notas[0,1]
notas[0,2]
notas[19,9]
...
Inicializações automáticas:
Tipo primitivo
Numérico: 0
Booleano: false
Tipo referência: null (Ex: String)
Matriz é um objeto (array de arrays)
Nome da matriz é referência para objeto
Matrizes Declaração 1/4
Nelson Freire (ISEP–DEI-APROG 2012/13) 8/28
// Algoritmia
ED
INTEIRO numLin, numCol, notas[20][10], mat[][]
INÍCIO
...
numLin lerNumero("Linhas") // lerNumero é função do programa
numCol lerNumero("Colunas")
criar mat[numLin][numCol]
...
FIM
...
// Java
public class Exemplo_1 {
public static void main(String[] args) {
int notas[][] = new int[20][10]; // matriz criada; elementos inicializados a 0 ...
int numLin = lerNumero("Linhas"); // lerNumero é função do programa
int numCol = lerNumero("Colunas");
int mat[][] = new int[numLim][numCol];
...
}
...
}
Matrizes Declaração 2/4
Exemplos
Nelson Freire (ISEP–DEI-APROG 2012/13) 9/28
// Algoritmia
ED
REAL mat1[][]
INTEIRO[][] mat2
INÍCIO
...
criar mat1[10][30]
...
criar mat2[5][10]
FIM
// Java
public class Exemplo_2 {
public static void main(String[] args) {
...
double mat1[][]; // declarada variável mat1 para representar matriz ...
mat1 = new double[10][30]; // matriz criada e atribuída a mat1 // elementos inicializados a zero ...
int[][] mat2 = new int[5][10];
}
}
Matrizes Declaração 3/4
Exemplos
Nelson Freire (ISEP–DEI-APROG 2012/13) 10/28
// Java
public class Exemplo_3 {
public static void main(String[] args) {
int matriz[][] = {{10,12,15},{19,9,18}}; // criada e inicializada uma matriz 2x3 ...
}
}
Matrizes Declaração 4/4
Exemplos
// Algoritmia
ED
INTEIRO matriz[][]
INÍCIO
matriz {{10,12,15},{19,9,18} } // criada e inicializada uma matriz 2x3 ...
FIM
linha 0 linha 1 10 12 15
19 9 18
Nelson Freire (ISEP–DEI-APROG 2012/13) 11/28
Nome da Matriz
Referência de um array Guarda referências de outros arrays // podem ter dimensões diferentes
Representam linhas da matriz Constituem os elementos da matriz
Exemplo
int[][] mat = new int[3] [3];
Representação RAM
// referência = endereço
1 2 3
4 5 6
7 8 9
referência
mat
mat[0]
referência
1
mat[0][0]
2
mat[0][1]
3
mat[0][2]
4
mat[1][0]
5
mat[1][1]
6
mat[1][2]
7
mat[2][0]
8
mat[2][1]
9
mat[2][2]
mat[1]
referência mat[2]
ARRAYS
ARRAY
mat[x].length (x=0, 1 ou 2)
mat.length
ARRAY
ARRAY
ARRAY
referência
Matrizes Java : Matriz é um Array de Arrays
Nelson Freire (ISEP–DEI-APROG 2012/13) 12/28
Elemento
Pode ser manipulado individualmente
Funciona como variável simples
Identificado
Nome da matriz
Índices de linha e coluna respetivos
Indicar um elemento
Algoritmia
Sintaxe: nomeMatriz [índiceLinha] [índiceColuna]
Ex: notas[0][2]
Manipulação de Elementos
Um elemento
Todos os elementos
Java
nomeMatriz [índiceLinha] [índiceColuna];
notas[0][2]
Matrizes Manipulação de Elementos
RAM
notas[0,0]
notas[0,1]
notas[0,2]
notas[19,9]
...
Nelson Freire (ISEP–DEI-APROG 2012/13) 13/28
Algoritmia
Atribuir um valor a um elemento
Ex: guardar ou actualizar um elemento
Sintaxe: nomeMatriz[índice Linha][índice Coluna] valor
Ex: notas[0][2]18
Atribuir o valor de um elemento a uma variável
Sintaxe: variável nomeMatriz[índice Linha][indice Coluna]
Ex: x notas[0][2]
// x do tipo INTEIRO
Java
nomeMatriz[í. Linha][í. Coluna] = valor;
notas[0][2] = 18;
variável=nomeMatriz[í. Linha][í.Coluna];
x = notas[0][2];
// x do tipo int
Matrizes Manipulação de um Elemento
Nelson Freire (ISEP–DEI-APROG 2012/13) 14/28
Algoritmia
Indicar todos os elementos (matriz n x m)
PARA (i0 ATÉ n-1 PASSO 1) FAZER PARA (j0 ATÉ m-1 PASSO 1) FAZER
... nomeMatriz[i][j] ...
FPARA FPARA
Exemplo
Preencher toda a matriz notas (n x m) com valores lidos do teclado
PARA (i0 ATÉ n-1 PASSO 1) FAZER PARA (j0 ATÉ m-1 PASSO 1) FAZER
LER( notas[i][j] )
FPARA FPARA
Java
for(i=0; i< nomeMatriz.length; i++){
for(j=0; j< nomeMatriz[i].length; j++){ ... nomeMatriz[i][j] ...
}
}
for(i=0; i<notas.length; i++){
for(j=0; j<notas[i].length; j++){
notas[i][j]=ler.nextInt();
} }
nomeMatriz.length (nº linhas)
nomeMatriz[i].length (nº cols linha i)
Matrizes Manipulação de todos os Elementos
Nelson Freire (ISEP–DEI-APROG 2012/13) 15/28
Em Java
Matriz é objeto basta transferir referência desse objeto indicar nome da matriz
Exemplo
Matrizes Transferência entre Módulos/Métodos 1/5
int[ ][ ] mat = new int[3][3]; nome da matriz (objeto)
referência
mat
mat[0]
referência
1
mat[0][0]
2
mat[0][1]
3
mat[0][2]
4
mat[1][0]
5
mat[1][1]
6
mat[1][2]
7
mat[2][0]
8
mat[2][1]
9
mat[2][2]
mat[1]
referência mat[2]
ARRAYS
(objetos)
ARRAY
(objeto) mat[2].length
mat.length
ARRAY
ARRAY
ARRAY
referência
Nelson Freire (ISEP–DEI-APROG 2012/13) 16/28
Formas de Transferir uma Matriz
Passagem de parâmetros
Retorno da função
DEFINIR tipo_retornado nome (..., tipo[ ][ ] nomeMatriz, ...) ED // variáveis e constantes locais
INÍCIO // corpo da função
RETORNAR expressão_tipo_retornado FDEF
DEFINIR nome (..., tipo nomeMatriz [ ][ ], ...) ED // variáveis e constantes locais
INÍCIO // corpo do procedimento
FDEF
Procedimento
Função
DEFINIR tipo[ ][ ] nome (...) ED tipo[ ][ ] nomeMatriz INÍCIO // corpo da função
RETORNAR nomeMatriz FDEF
Função
Matrizes Transferência entre Módulos/Métodos 2/5
Nelson Freire (ISEP–DEI-APROG 2012/13) 17/28
Passagem de Parâmetros
Passada cópia da referência da matriz
Módulo acede à matriz original Pode modificar a matriz original
Parâmetro formal funciona como parâmetro de entrada e de saída
Declaração de um parâmetro formal
Para receber a referência da matriz
Algoritmia
Sintaxe: tipo nomeMatriz[][]
ou
tipo[][] nomeMatriz
Ex: DEFINIR ler( INTEIRO matriz[ ][ ] , ...) ...
Chamada de um módulo
Passar referência da matriz (i.e., nome da matriz)
Algoritmia
Sintaxe: nomeMatriz
Ex: ler(notas, ...)
Java
tipo nomeMatriz[][];
ou
tipo[][] nomeMatriz
public static void ler( int matriz[ ][ ], ...){...}
Java
nomeMatriz
ler(notas, ...);
Matrizes Transferência entre Módulos/Métodos 3/5
DEFINIR tipo nome(..., tipo nomeMatriz [ ][ ], ...)
Nelson Freire (ISEP–DEI-APROG 2012/13) 18/28
Retorno da Função
Retornada referência da matriz
Declaração do tipo_retornado da função
Tipo matriz
Algoritmia
• Sintaxe: DEFINIR tipo[ ][ ] nomeFunção ( ...) ...
Ex: DEFINIR INTEIRO[ ][ ] filtrar(...) ...
Retorno
Referência da matriz (i.e., nome da matriz)
Algoritmia
Sintaxe: RETORNAR nomeMatriz
Ex: RETORNAR notas
Java
public static tipo[ ][ ] nomeMétodo(...){...};
public static int[ ][ ] filtrar(...){...}
Java
return nomeMatriz;
return notas;
Matrizes Transferência entre Módulos/Métodos 4/5
DEFINIR tipo[ ][ ] nome(...) ED tipo[ ][ ] nomeMatriz INÍCIO // corpo da função
RETORNAR nomeMatriz FDEF
Nelson Freire (ISEP–DEI-APROG 2012/13) 19/28
Exemplo
import java.util.Scanner;
public class Exemplo {
public static void main(String[] args) {
int numLin = lerNumero("linhas");
int numCol = lerNumero("colunas");
int[][] m1 = new int[numLin][numCol];
lerMatriz(m1);
int[][] m2 = clonar(m1);
mostrarMatriz(m1);
mostrarMatriz(m2);
}
private static void lerMatriz(int[][] mat) {
Scanner ler = new Scanner(System.in);
System.out.println("\nDigite nº inteiros:");
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print((i+1)+ "," +(j+1) +":");
mat[i][j] = ler.nextInt();
}
}
}
private static void mostrarMatriz(int[][] mat){
System.out.println("\nMatriz:")
for (int i = 0; i < mat.length; i++){
for (int j = 0; j < mat[i].length; j++)
System.out.printf("%6d",mat[i][j]);
System.out.println();
}
}
private static int[][] clonar(int[][] mat1){
int[][] mat2;
mat2 = new int[mat1.length][mat1[0].length];
for (int i = 0; i < mat1.length; i++) {
for (int j = 0; j < mat1[i].length; j++)
mat2[i][j] = mat1[i][j];
return mat2;
}
private static int lerNumero(String s){
Scanner ler = new Scanner(System.in);
System.out.print("\nInsira o nº de "+s+":");
int n = ler.nextInt();
while (n<=0) {
System.out.println("Valor Inválido!!" +
"Insira novo nº de "+s+":");
n = ler.nextInt();
}
return n;
}
}
Matrizes Transferência entre Módulos/Métodos 5/5
Nelson Freire (ISEP–DEI-APROG 2012/13) 20/28
ED
INTEIRO soma, lin, col, matriz[][]
INÍCIO
matriz {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
soma 0
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
PARA (col0 ATÉ comprimentoColunas(matriz,lin)-1 PASSO 1) FAZER
soma soma + matriz[lin][col]
FPARA
FPARA
ESCREVER("A soma de todos os elementos é ", soma)
FIM
public class SomaGlobal {
public static void main(String[] args) {
int matriz[][] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
int soma=0;
for (int lin = 0; lin < matriz.length; lin++) {
for (int col = 0; col < matriz[lin].length; col++) {
soma = soma + matriz[lin][col];
}
}
System.out.println("A soma de todos os elementos é " + soma);
}
}
Matrizes (Exemplos) Soma Global
Funções pré-definidas comprimentoLinhas comprimentoColunas
Nelson Freire (ISEP–DEI-APROG 2012/13) 21/28
ED
INTEIRO soma, lin, col, matriz[][]
INÍCIO
matriz {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
soma 0
PARA (col0 ATÉ comprimentoColunas(matriz,lin)-1 PASSO 1) FAZER
soma soma + matriz[lin][col]
FPARA
ESCREVER("A soma da linha ", lin, " é ", soma)
FPARA
FIM
public class SomaLinha {
public static void main(String[] args) {
int matriz[][] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
for (int lin = 0; lin < matriz.length; lin++) {
int soma=0;
for (int col = 0; col < matriz[lin].length; col++) {
soma = soma + matriz[lin][col];
}
System.out.println("A soma da linha " + lin + " é " + soma);
}
}
}
Matrizes (Exemplos) Soma de Cada Linha
Nelson Freire (ISEP–DEI-APROG 2012/13) 22/28
ED
INTEIRO soma, lin, col, matriz[][]
INÍCIO
matriz {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
PARA (col0 ATÉ comprimentoColunas(matriz,0)-1 PASSO 1) FAZER
soma 0
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
soma soma + matriz[lin][col]
FPARA
ESCREVER("A soma da coluna ", col, " é ", soma)
FPARA
FIM
public class SomaColuna {
public static void main(String[] args) {
int matriz[][] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
for (int col = 0; col < matriz[0].length; col++) {
int soma=0;
for (int lin = 0; lin < matriz.length; lin++) {
soma = soma + matriz[lin][col];
}
System.out.println("A soma da coluna " + col + " é ", soma);
}
}
}
Matrizes (Exemplos) Soma de Cada Coluna
Nelson Freire (ISEP–DEI-APROG 2012/13) 23/28
ED
INTEIRO soma, lin, matriz[][]
INÍCIO
matriz {{1,2,3},{4,5,6},{7,8,9}}
soma 0
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
soma soma + matriz[lin][lin]
FPARA
ESCREVER("A soma da diagonal principal é ", soma)
FIM
public class SomaDiagonalPrincipal{
public static void main(String[] args) {
int matriz[][] = {{1,2,3},{4,5,6},{7,8,9}};
int soma=0;
for (int lin = 0; lin < matriz.length; lin++) {
soma = soma + matriz[lin][lin];
}
System.out.println("A soma da diagonal principal é " + soma);
}
}
Matrizes (Exemplos) Soma da Diagonal Principal
1 2 3
4 5 6
7 8 9
Nelson Freire (ISEP–DEI-APROG 2012/13) 24/28
ED
INTEIRO maior, lin, col, matriz[][]
INÍCIO
matriz {{1,18,3},{4,17,6},{7,28,9},{10,11,12}}
maior matriz[0][0]
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
PARA (col0 ATÉ comprimentoColunas(matriz,lin)-1 PASSO 1) FAZER
SE ( matriz[lin][col] > maior ) ENTÃO
maior matriz[lin][col]
FSE
FPARA
FPARA
ESCREVER("O maior número global é ", maior)
FIM
public class MaiorGlobal {
public static void main(String[] args) {
int matriz[][] = {{1,18,3},{4,17,6},{7,28,9},{10,11,12}};
int maior = matriz[0][0];
for (int lin = 0; lin < matriz.length; lin++) {
for (int col = 0; col < matriz[lin].length; col++)
if( matriz[lin][col] > maior )
maior = matriz[lin][col];
}
System.out.println("O maior número global é ", maior);
}
}
Matrizes (Exemplos) Maior Global
Nelson Freire (ISEP–DEI-APROG 2012/13) 25/28
ED
INTEIRO maior, lin, col, matriz[][]
INÍCIO
matriz {{1,18,3},{4,17,6},{7,28,9},{10,11,12}}
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
maior matriz[lin][0]
PARA (col1 ATÉ comprimentoColunas(matriz,lin)-1 PASSO 1) FAZER
SE ( matriz[lin][col] > maior ) ENTÃO
maior matriz[lin][col]
FSE
FPARA
ESCREVER("O maior número da linha ", lin, " é ", maior)
FPARA
FIM
public class MaiorLinha {
public static void main(String[] args) {
int matriz[][] = {{1,18,3},{4,17,6},{7,28,9},{10,11,12}};
for (int lin = 0; lin < matriz.length; lin++) {
int maior = matriz[lin][0];
for (int col = 1; col < matriz[lin].length; col++)
if( matriz[lin][col] > maior )
maior = matriz[lin][col];
System.out.println("O maior número da linha ", lin, " é ", maior);
}
}
}
Matrizes (Exemplos) Maior de Cada Linha
Nelson Freire (ISEP–DEI-APROG 2012/13) 26/28
ED
INTEIRO maior, lin, col, matriz[][]
INÍCIO
matriz {{1,18,3},{4,17,6},{7,28,9},{10,11,12}}
PARA (col0 ATÉ comprimentoColunas(matriz,0)-1 PASSO 1) FAZER
maior matriz[0][col]
PARA (lin1 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
SE ( matriz[lin][col] > maior ) ENTÃO
maior matriz[lin][col]
FSE
FPARA
ESCREVER("O maior número da coluna ", col, " é ", maior)
FPARA
FIM
public class MaiorColuna {
public static void main(String[] args) {
int matriz[][] = {{1,18,3},{4,17,6},{7,28,9},{10,11,12}};
for (int col = 0; col < matriz[0].length; col++) {
int maior = matriz[0][col];
for (int lin = 1; lin < matriz.length; lin++)
if( matriz[lin][col] > maior )
maior = matriz[lin][col];
System.out.println("O maior número da coluna ", col, " é ", maior);
}
}
}
Matrizes (Exemplos) Maior de Cada Coluna
Nelson Freire (ISEP–DEI-APROG 2012/13) 27/28
ED
INTEIRO lin, col, matriz[][], transposta[][]
INÍCIO
matriz {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}
criar transposta[comprimentoColunas(matriz,0)][comprimentoLinhas(matriz)]
PARA (lin0 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
PARA (col0 ATÉ comprimentoColunas(matriz,lin)-1 PASSO 1) FAZER
transposta[col][lin]matriz[lin][col]
FPARA
FPARA
FIM
public class MatrizTransposta {
public static void main(String[] args) {
int matriz[][] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
int transposta[][] = new int[matriz[0].length][matriz.length];
for (int lin = 0; lin < matriz.length; lin++) {
for (int col = 0; col < matriz[lin].length; col++) {
transposta[col][lin] = matriz[lin][col];
}
}
}
}
Matrizes (Exemplos) Matriz Transposta
Nelson Freire (ISEP–DEI-APROG 2012/13) 28/28
ED
INTEIRO i, j, matriz[][], tmp[]
INÍCIO
matriz {{1,2,3},{7,8,9},{10,11,12},{4,5,6}}
PARA (i0 ATÉ comprimentoLinhas(matriz)-2 PASSO 1) FAZER
PARA (ji+1 ATÉ comprimentoLinhas(matriz)-1 PASSO 1) FAZER
SE (matriz[j][0] > matriz[i][0]) ENTÃO
tmp matriz[i]
matriz[i] matriz[j]
matriz[j] tmp
FSE
FPARA
FPARA
FIM
public class MatrizOrdenada {
public static void main(String[] args) {
int matriz[][] = {{1,2,3},{7,8,9},{10,11,12},{4,5,6}};
for (int i = 0; i < matriz.length-1; i++)
for (int j = i+1; j < matriz.length; j++)
if( matriz[j][0] > matriz[i][0]){
int[] tmp = matriz[i]; // matriz[i] é a linha i
matriz[i] = matriz[j];
matriz[j] = tmp;
}
}
}
Matrizes (Exemplos) Matriz Ordenada
Linhas ordenadas por ordem decrescente dos elementos da primeira coluna