




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Pontif´ıcia Universidade Cat´olica de Minas Gerais Bacharelado em Ciˆencia da Computa¸c˜ao Algoritmos e Estruturas de Dados II Prof. Fabio Tirelo
Ultima atualiza¸^ ´ c˜ao: 20 de Julho de 2005
Fatores M´ınimos de Qualidade
Modularidade
Abstra¸c˜ao: ato de descartar o que ´e acidental, detalhe ou pr´oprio do modo de resolver, concentrando-se no que ´e relevante, es- sencial, ou pr´oprio de uma especifica¸c˜ao.
import aed2.Util;
// ´Indice da tabela ´e o n´umero de matr´ıcula public class TabelaAlunos { private int maxMatric; private String alunos []; public TabelaAlunos(int nd) { Util. valida (nd > 0, ”N´umero de d´ıgitos inv´alido ”); int nPos = (int) (Math.pow(10, nd) + 0.5); alunos = new String[nPos]; maxMatric = nPos − 1; } public void adicionaAluno(int matr, String nome) { Util. valida (matr >= 0 && matr < maxMatric, ”N´umero de matr´ıcula inv´alido!”); alunos [matr] = nome; } public String obtemAluno(int matr) { Util. valida (matr >= 0 && matr < maxMatric, ”N´umero de matr´ıcula inv´alido!”); return alunos[matr]; } }
class Aluno { public int matr; public String nome; public Aluno(int mat, String n) { matr = mat; nome = n; } }
import aed2.Util; // Vetor de pares ( matr´ıcula ,nome) public class TabelaAlunos { private int nElem; private Aluno alunos []; public TabelaAlunos(int tam) { nElem = 0; alunos = new Aluno[tam]; } public void adicionaAluno(int matr, String nome) { ... } public String obtemAluno(int matr) { ... } }
// Vetor de pares ( matr´ıcula ,nome), ordenado por matr´ıcula
// Realiza inser¸c˜ao ordenada no vetor public void adicionaAluno(int matr, String nome) {
Util. valida (matr > 0, ”Matr´ıcula inv´alida ”); Util. valida (nElem < alunos.length, ”Ultrapassou tamanho do vetor”);
int cont = nElem − 1; while (cont >= 0 && alunos[cont].matr > matr) { alunos [cont+1] = alunos[cont]; cont++; }
alunos [cont] = new Aluno(matr, nome); nElem++;
}
// Realiza pesquisa bin´aria no vetor public String obtemAluno(int matr) {
Util. valida (matr > 0, ”Matr´ıcula inv´alida ”);
boolean encontrado = false; int inf = 0, sup = nElem − 1, meio = (nElem − 1)/2;
while (! encontrado && inf <= sup) {
meio = (inf + sup)/2; if (alunos [meio].matr == matr) encontrado = true; else if (alunos [meio].matr < matr) inf = meio + 1; else sup = meio − 1;
}
if (encontrado) return alunos[meio].nome; else return null;
}
Defini¸c˜ao: Uma Pilha ´e um conjunto de elementos no qual o ´unico elemento acess´ıvel ´e o elemento inserido h´a menos tempo, denominado topo.
Ao se retirar um elemento de uma pilha, retira-se sempre o elemento do topo.
Opera¸c˜oes:
Implementa¸c˜ao como vetor de tamanho fixo:
Stack-Empty(S)
1 if top[S] = 0 2 then return true 3 else return false
Push(S, x)
1 top[S] ← top[S] + 1 2 S[top[S]] ← x
Pop(S)
1 if Stack-Empty(S) 2 then error “underflow” 3 else top[S] ← top[S] − 1 4 return S[top[S] + 1]
public static Stack p2p n(Stack S) { Stack result = new Stack(), aux = new Stack(); while (! S.empty()) aux.push(S.pop()); while (! aux.empty()) { int val = aux.pop(); S.push(val ); result .push(val ); } return result ; }
public static Stack p2p i(Stack S) { Stack result = new Stack(), aux = new Stack(); while (! S.empty()) { int val = S.pop(); aux.push(val ); result .push(val ); } while (! aux.empty()) S.push(aux.pop()); return result ; }
Implementa¸c˜ao utilizando vetores flex´ıveis public class Stack { private static final int DEFAULT SIZE = 10; private int store [], top; public Stack(int maxElements) { store = new int[maxElements + 1]; } public Stack() { this(DEFAULT SIZE); } public boolean empty() { return top == 0; } public void push(int element) { if (top == store.length − 1) grow(); store [++top] = element; } private void grow() { int oldstore [] = store; store = new int[2 ∗ oldstore. length ]; for (int i = 0; i < oldstore. length ; i++) store [ i ] = oldstore [ i ]; } public int pop() { Util. valida (! empty(), ”UNDERFLOW”); return store [top−−]; } }
public class SomaNumerosGrandes { public static void main(String [] args) { Stack stk1 = strToStack(”6897890123456”); Stack stk2 = strToStack(”5897890123456”); Stack stkRes = soma(stk1, stk2); System.out. println (stackToStr(stkRes )); } private static String stackToStr(Stack stkRes) { String res = ””; while (! stkRes.empty()) res += stkRes.pop(); return res; } private static Stack soma(Stack stk1, Stack stk2) { Stack result = new Stack(); int vaium = 0; while (! stk1 .empty() ||! stk2 .empty()) { int val1 = stk1.empty()? 0 : stk1 .pop(); int val2 = stk2.empty()? 0 : stk2 .pop(); int res = val1 + val2 + vaium; result .push(res % 10); vaium = res / 10; } if (vaium > 0) result .push(vaium); return result ; } private static Stack strToStack( String strNum) { Stack stkNum = new Stack(strNum.length()); for (int i = 0; i < strNum.length(); i++) stkNum.push(strNum.charAt(i) − ’0’); return stkNum; } }
Considere um labirinto armazenado em um arquivo texto da seguinte maneira:
11 11 11 11 x x x x x x x x x x x x x x x x x x x x x x x x x x..... x x x x x x x x. x... x x x E x x x E. x..... x x x x x x x x x x x x x x x x. x x x x x x x x x x... x x x x x x x x. x x x x x x x x x x x x x x. x x x x M x x x x x M x. x x x x x x... x x x x x x x x x x x x x x x x x x x x x x x x
Legenda:
O objetivo ´e fazer com que o rato encontre a sa´ıda.
public class Position { private int row, column; public Position (int row, int column) { this .row = row; this.column = column; } public int getColumn() { return column; } public void setColumn(int column) { this .column = column; } public int getRow() { return row; } public void setRow(int row) { this .row = row; } public String toString () { return ”(” + row + ”,” + column + ”)”; } }
public class MazeProgram { public static void main(String [] args) throws FileNotFoundException, IOException { Maze maze = new Maze(”teste.txt”); maze.findExitPath (); } }
public class Maze { // Constantes private static final char MOUSE = ’M’; private static final char EXIT = ’E’; private static final char FREE = ’ ’; private static final char VISITED = ’.’; private static final char WALL = ’x’; // Atributos da classe private char mazeTable [][]; private Position aux [][], posMouse, posExit; private int nRows, nColumns; // Construtor public Maze(String fileName) throws FileNotFoundException, IOException { ... } // M´etodo da interface : p´ublico public void findExitPath () { ... } // M´etodos auxiliares : privados private void readPosition (int row, String strRow, int column) { ... } private void allocMazeTable(String strSize ) { ... } private void showPath() { ... } private void showMazeTable() { ... } private void clearMazeTable() { ... } private void pushUnvisited(Stack s , Position p, int row, int col ) { ... } private void markMouseAndExit() { ... } private void markPath() { ... } }