Escolar Documentos
Profissional Documentos
Cultura Documentos
Programação Multimédia
3. Estruturas de Dados
Estruturas de Dados
• Estáticas:
• Exemplo: arrays
• Dinâmicas:
• Exemplo: ArrayLists
fi
fi
LDM Programação Multimédia Estruturas de Dados 3
• Unidimensionais:
0 1 2 3 4 a.length-1
a:
a.length
LDM Programação Multimédia Estruturas de Dados 4
• Bidimensionais:
a[2][0]
a: 0 1 2 3 a.length-1
0
1
a[0].length
a[0].length-1
a.length a[3][2]
Consultar Shi man, Cap. 9
ff
LDM Programação Multimédia Estruturas de Dados 5
lista.size()-1
0 1
lista
lista.size()
ArrayList de objetos
Inicialmente vazia
• Criação:
lista.size()-1
0 1
lista
lista.size()
LDM Programação Multimédia Estruturas de Dados 7
Principais métodos
boolean add(Classe o) Appends the specified element to the end of this list.
void add(int index, Classe o) Inserts the specified element at the specified position in this list.
boolean contains(Classe o) Returns true if this list contains the specified element.
Class get(int index) Returns the element at the specified position in this list.
int indexOf(Classe o) Returns the index of the first occurrence of the specified element in this
list, or -1 if this list does not contain the element.
boolean isEmpty() Returns true if this list contains no elements.
Class remove(int index) Removes the element at the specified position in this list.
boolean remove(Classe o) Removes the first occurrence of the specified element from this list, if it
is present.
int size() Returns the number of elements in this list.
void trimToSize() Trims the capacity of this ArrayList instance to be the list's current size.
• Criar uma ArrayList com 10 objetos de uma classe Bola com construtor
Bola(float x, float y, float d, color cor
void setup() {
(…)
for(int i = 0; i<10; i++)
b.add(new Bola(random(100,400), random(100,400), 15, color(0));
(…)
• lista.add(obj);
void draw(){
background(255);
for(int i = 0; i < b.size(); i++){
b.get(i).desenha();
b.get(i).step();
}
}
• obj = lista.get(i);
void setup() {
adiciona 3 bolas
size(500,500);
for(int i = 0; i<3; i++) {
b.add(new Bola(0, height/2, d, cores[proxCor]));
proxCor++;
}
void draw(){
background(255);
for(int i = 0; i < b.size(); i++){
b.get(i).x = (i+1)*distH;
b.get(i).desenha();
}
}
• lista.add(34)
• lista.add(0, 53);
;
fl
;
Exemplo:
ArrayList <Integer> a = new ArrayList();
void setup() {
size(500,500);
for(int i = 0; i<5; i++) {
a.add(round(random(width)));
}
void draw() {
background(255);
ll(0);
int passo = round(height/(a.size()+1));
// primeira bolinha
circle(a.get(0), passo, 5);
//Restantes bolinhas e linhas
for(int i = 1; i<a.size(); i++) {
circle(a.get(i), (i+1)*passo, 5);
line(a.get(i), (i+1)*passo, a.get(i-1), i*passo);
}
}
fi
Outros métodos
lista.size()
• Posição de um elemento na lista:
Uma classe
• A classe PVector (pré-de nida) pode ser usada para representar pontos num plano:
• x —> coordenada em x
• y —> coordenada em y
• Mais tarde voltaremos a esta classe para a explorarmos com mais atenção.
fi
LDM Programação Multimédia Estruturas de Dados 17
alternativa
Exemplo
reta i
LDM Programação Multimédia Estruturas de Dados 22
void mousePressed()
if(p < nlinhasmax*2) void keyPressed()
x[p] = mouseX if (keyCode == ' ')
y[p] = mouseY; p=0
p++
pt
reta i
LDM Programação Multimédia Estruturas de Dados 24
void mousePressed()
if(p < nlinhasmax*2)
pt[p] = new PVector(mouseX, mouseY); void keyPressed()
p++ if (keyCode == ' ')
p=0
} }
}
ArrayList pt
reta i
LDM Programação Multimédia Estruturas de Dados 26
void draw()
ArrayList<PVector> pt = new ArrayList() background(255);
for (int i=0; i < pt.size(); i++)
void setup () fill(0)
size(500, 500) circle(pt.get(i).x, pt.get(i).y, 5)
if (i%2 != 0
line(pt.get(i-1).x, pt.get(i-1).y
void mousePressed() pt.get(i).x, pt.get(i).y)
pt.add(new PVector(mouseX, mouseY))
}
void keyPressed()
if (keyCode == ' ')
pt.clear()
}
}
void setup()
size(500,500)
for(int i = 0; i<100; i++
b.add(new Bola(random(width),
random(height), 25, color(200))
void draw()
background(255)
stroke(255,0,0)
line(0, height/2, width, height/2)
stroke(0)
for(int i = 0; i < b.size(); i++)
b.get(i).desenha()
}
}
void mousePressed()
for (int i=0; i<b.size(); i++
if(b.get(i).y > height/2
b.remove(i)
}
• Apagar verdes:
0 1 2 3 4 5 6 7 8 9
i i i
0 1 2 3 4 5 6 7 8
i
0 1 2 3 4 5 6 7
i
Ficou por apagar!
LDM Programação Multimédia Estruturas de Dados 30
Solução:
void mousePressed()
for (int i=b.size()-1; i>=0; i--
if(b.get(i).y > height/2
b.remove(i)
}
Dicionário
Chave Valor
Key 1 Value 1
Key 2 Value 2
Key 3 Value 3
… …
Key n Value n
• Construtor:
• Adicionar entrada:
• dic.set("farinha", 38);
• Remover entrada:
• dic.remove("farinha");
LDM Programação Multimédia Estruturas de Dados 33
Métodos Funcionalidade
void set(String key, Integer value) Adiciona novo par chave/valor, ou altera valor de par existente
int get(String key) Devolve valor associado à chave
int size( ) Devolve número de pares do dicionário
String [ ] keyArray( ) Devolve cópia do array de chaves interno
String [ ] valueArray( ) Devolve cópia do array de valores interno
boolean hasKey(String key) Verifica se a chave existe no dicionário
void increment(String key) Incrementa valor associado a uma chave
void remove(String key) Remove par com a chave dada
void clear( ) Apaga todos os pares existentes
void sortKeys( ) Ordena chaves alfabeticamente
void sortKeysReverse( ) Ordena chaves alfabeticamente por ordem inversa
void sortValues( ) Ordena por valores crescentes
void sortValuesReverse( ) Ordena por valores decrescentes
LDM Programação Multimédia Estruturas de Dados 34
Exemplo 1:
IntDict inventory
void setup()
size(200, 200)
inventory = new IntDict()
inventory.set("cds", 84)
inventory.set("livros", 15) Adiciona pares
inventory.set("vinis", 102)
println("Inicial: "+inventory)
if (inventory.hasKey("vinis"))
println("Sim, temos “ + inventory.get(“vinil”) + “ vinis.");
} else
println("Desculpe, não temos vinis.")
Exemplo 2:
IntDict inventory
void setup()
size(200, 200)
inventory = new IntDict()
inventory.set("cds", 84)
inventory.set("livros", 15)
inventory.set("vinis", 102)
println("Inicial: "+inventory)
inventory.remove("livros")
println("Final: "+inventory); Remove par
}
Exemplo 3:
IntDict inventory
void setup()
size(200, 200)
inventory = new IntDict()
inventory.set("cds", 84)
inventory.set("livros", 15)
inventory.set("vinis", 102)
println("Inicial: "+inventory)
inventory.set("cds", 8)
println("Final: "+inventory); Altera valor
println("cds: "+ inventory.get("cds"));
}
cds: 8
{
Exemplo 4:
IntDict inventory
void setup()
size(200, 200)
inventory = new IntDict()
inventory.set("cds", 84)
inventory.set("livros", 15)
inventory.set("vinis", 102)
cds 84
livros 15
vinis 102
{
• Construtor:
• Adicionar entrada:
• dic.set("farinha", “branca");
• Remover entrada:
• dic.remove("farinha");
LDM Programação Multimédia Estruturas de Dados 39
Exemplo 5:
StringDict loja
void setup()
size(200, 200)
loja = new StringDict()
loja.set("farinha", "branca")
loja.set("cafe", "preto")
loja.set("alface", "verde")
loja.set("manteiga", "amarela")
cafe preto
farinha branca
manteiga amarela
{
Exemplo 6:
balada_da_neve.txt
void setup()
linhas = loadStrings(texto)
for (int i=0; i<linhas.length; i++)
palavras = splitTokens(linhas[i], " ,.?:")
for (int p=0; p<palavras.length; p++
if(dicP.hasKey(palavras[p])
dicP.increment(palavras[p]) Conta ocorrências
else dicP.set(palavras[p], 1)
Ordena
dicP.sortValuesReverse()
String[] pals = dicP.keyArray() (val. decrescentes) é ocorre 4 vezes
}
Será ocorre 2 vezes
se ocorre 2 vezes
Mostra 5 mais frequentes
}