miércoles, 29 de abril de 2009

Programa 4.

Programa_arboles

//Definicion de la clase lista
class ListaSimpleEst{
String impresor="";
NodosListaEst PrimerNodo;
NodosListaEst UltimoNodo;
//Retorna True si lista Vacia
public boolean VaciaLista(){
return PrimerNodo ==null;
}
//Inserta al final de la lista (solo prestamos)
public void InsertaFinal(int ide,int cod,String nom,NodosListaEstCursos a){
if(VaciaLista()){
PrimerNodo= UltimoNodo = new NodosListaEst (ide,cod,nom,a);
System.out.println("Se inserto estudiante "+ide+nom);
}
else{
UltimoNodo=UltimoNodo.siguiente=new NodosListaEst (ide,cod,nom,a);
System.out.println("Se inserto estudiante "+ide+" "+nom);
}
}

//elimina el ultimo elemento
public void EliminaFinal (){
if(!VaciaLista()){
if(PrimerNodo.equals(UltimoNodo))
PrimerNodo = UltimoNodo = null;
else{
NodosListaEst Actual=PrimerNodo;
while(Actual.siguiente != UltimoNodo)
Actual = Actual.siguiente;
UltimoNodo =Actual;
Actual.siguiente = null;
}
}
}
//Miembro
public boolean Miembro (int ele){
boolean enc=false;
NodosListaEst aux=PrimerNodo;
while((aux != null) && (enc==false)){
if(ele==aux.ident){
enc=true;
}
else{
aux=aux.siguiente;
}
}
return enc;
}
//Nombre
public String CualNombre (int ele){
String x="";
boolean enc=false;
NodosListaEst aux=PrimerNodo;
while((aux != null) && (enc==false)){
if(ele==aux.ident){
enc=true;
x=aux.Nombre;
}
else{
aux=aux.siguiente;
}
}
return x;
}
//imprime
public void Imprimir(){
if (VaciaLista()){
impresor="error";
}
else{
NodosListaEst Actual = PrimerNodo;
while (Actual != null){
impresor=impresor+"Id: "+Actual.ident+"\nNombre: "+Actual.Nombre+"\nCod Carrera: "+Actual.Codcar+"\nCursos: ";
NodosListaEstCursos aa=Actual.cursos;
while(aa!=null){
impresor=impresor+aa.curso+" ";
aa=aa.siguiente;
}
impresor=impresor+"\n--------------------------\n";
Actual=Actual.siguiente;
}
}
}
// Largo
public void Largo(){
NodosListaEst aux=PrimerNodo;
int Lar =0;
while (aux!= null){
Lar++;
aux =aux.siguiente;
}
System.out.println ( "El largo de la Lista es: "+ Lar);
}
}
//Nodo de lista simple
class NodosListaEst{
int ident;
int Codcar;
String Nombre;
NodosListaEstCursos cursos;
NodosListaEst siguiente;
NodosListaEst (int ide,int cod,String nom,NodosListaEstCursos a){
ident=ide;
Codcar=cod;
Nombre=nom;
cursos=a;
siguiente=null;
}
NodosListaEst(){}
}
//lista de cursos
class NodosListaEstCursos{
int curso;
NodosListaEstCursos siguiente;
NodosListaEstCursos (int cur){
curso=cur;
siguiente=null;
}
NodosListaEstCursos(){}
}

Busqueda binaria

Implementación: Busqueda binaria

public int busquedaBinaria(int []a, int x)

{

int i=0, j=a.length-1;

while (i<=j)

{

int m=(i+j)/2;

if (x==a[m])

{

return m;

}

else if (x

{

j=m-1;

}

else

{

i=m+1;

}

}

return NO_ENCONTRADO; // NO_ENCONTRADO se define como -1

}

EL CODIGO EN JAVA PARA INSERTAR UN ELEMENTO

EL CODIGO EN JAVA PARA INSERTAR UN ELEMENTO

public void insertItem(Object k, Object e) throws InvalidKeyException {

if(!comp.isComparable(k))

throw new InvalidKeyException("Invalid Key");

Position z = T.add(new Item(k, e));

Position u;

while(!T.isRoot(z)) { // bubbling-up

u = T.parent(z);

if(comp.isLessThanOrEqualTo(key(u),key(z)))

break;

T.swapElements(u, z);

z = u;

}

}

EL CODIGO EN JAVA PARA ELIMINAR UN ELEMENTO:

public Object removeMin() throws PriorityQueueEmptyException {
    if(isEmpty())
        throw new PriorityQueueEmptyException("Priority Queue Empty!");
    Object min = element(T.root());
    if(size() == 1)
        T.remove();
    else {
        T.replaceElement(T.root(), T.remove());
        Position r = T.root();
        while(T.isInternal(T.leftChild(r))) {
            Position s;
            if(T.isExternal(T.rightChild(r)) || comp.isLessThanOrEqualTo(key(T.leftChild(r)),key(T.rightChild(r))))
                s = T.leftChild(r);
            else
                s = T.rightChild(r);
            if(comp.isLessThan(key(s), key(r))) {
                T.swapElements(r, s);
                r = s;
            }
            else
                break;
        }
    }
}

APLICACION DE PILAS

PROGRAMA4.

APLICACION DE PILAS

import java.io.*;

public class Pila{

public static BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));

public static final int MAX_LENGTH = 5;

public static String Pila[] = new String[MAX_LENGTH];

public static int cima = -1;

public static void main(String args[])throws IOException{

Menu();

}

public static void Menu()throws IOException{

System.out.println("\n\n\t\t\t=========Menu Manejo Pila=============");

System.out.println("\t\t\t= =");

System.out.println("\t\t\t= 1- Insertar elemento =");

System.out.println("\t\t\t= 2- Eliminar elemento =");

System.out.println("\t\t\t= 3- Buscar elemento =");

System.out.println("\t\t\t= 4- Imprimir pila =");

System.out.println("\t\t\t= 5- Actualizar valor en pila =");

System.out.println("\t\t\t= 6- Salir =");

System.out.println("\t\t\t======================================");

System.out.print("\t\t\tOpcion: ");

int op = Integer.parseInt(entrada.readLine());

Opciones(op);

}

public static void Opciones(int op)throws IOException{

switch(op){

case 1: Insertar();

break;

case 2: Eliminar();

break;

case 3: Buscar();

break;

case 4: Imprimir();

break;

case 5: Actualizar();

break;

case 6: System.exit(1);

break;

default:Menu();

break;

}

}

public static void Insertar()throws IOException{

System.out.print("\nDigite algo para la pila: ");

String dato = entrada.readLine();

Crear(dato);

}

public static void Crear(String dato)throws IOException{

if ((Pila.length-1)==cima){

System.out.println("Capacidad de la pila al limite\n\n\n");

Imprimir();

}else{

++cima;

}

Agregar(dato);

}

public static void Agregar(String dato)throws IOException{

Pila[cima]=dato;

Menu();

}

public static void Imprimir()throws IOException{

for(int i=Pila.length-1;i>=0;i--){

System.out.println(Pila[i]);

}

Menu();

}

public static void Eliminar()throws IOException{

if(cima== -1){

System.out.println("\n\n\nNo se puede eliminar, pila vacia !!!" );

}else{

Pila[cima] = null;

--cima;

}

Menu();

}

public static void Buscar()throws IOException{

System.out.println("\n\n\nDigite la cadena a buscar: ");

String cad = entrada.readLine();

for(int i=0;i

if(cad.equals(Pila[i])){

System.out.println("Elemento encontrado,posicion "+i);

break;

}else{

System.out.println("Elemento no encontrado :(");

}

}

Menu();

}

public static void Actualizar()throws IOException{

System.out.print("Digite el nombre del valor que desea actualizar: ");

String actual = entrada.readLine();

System.out.print("Digite el nombre del nuevo valor: ");

String nuevo = entrada.readLine();

for(int i=0;i

if(actual.equals(Pila[i])){

Pila[i]=nuevo;

break;

}else{

System.out.println("Elemento no encontrado :(");

}

}

Menu();

}

}

Programa pila de bolitas

Programa2. PILA DE BOLITAS
import java.awt.Color;

import java.awt.Graphics;

import javax.swing.JPanel;
public class Bolita {
private int x;
private int y;
private JPanel panel;
private Color color;
-


public Bolita(Color col, JPanel panel2) {
color = col;
panel = panel2;
}

public void modPos(int x_, int y_){
x = x_;
y = y_;
}

public void paint (Graphics g){

g = panel.getGraphics();

g.setColor(color);
g.fillOval(x,y,20,20);


}

public void setXORMode( Graphics g ){
g = panel.getGraphics();
g.fillOval(x,y,20,20);
g.clearRect(x, y, 20, 20);
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Color getColor() {
return color;
}

public void setColor(Color color) {
this.color = color;
}
}

//CLASE PILA DE BOLITAS (MANEJADOR)
[des]activar nros. de línea

import java.awt.*;
public class PilaDeBolitas {
private static final long serialVersionUID = 1L;
public static final int MAX = 10;

public class UnderFlowException extends Exception{

private static final long serialVersionUID = -9026952799388596808L;

}
public class OverFlowException extends Exception{

private static final long serialVersionUID = -5485402241073047658L;

}
// Atributos

private Bolita [] bolitas; // Arreglo que contiene los elementos
private int tope;

public int getTope() {
return tope;
}

public void paint(Graphics g) {

for(int i = 0; i <>

bolitas[i].paint(g);
}
}
public void setXORMode(Graphics g) {

for(int i = 0; i <>
bolitas[i].setXORMode(g);
}
}
public Bolita getTopeBolita(){
return bolitas[getTope()];
}
public PilaDeBolitas(){
//super("SUPER PAINT",false,false,false,false);
bolitas = new Bolita [MAX];
tope = 0;
}

public void apilar(Bolita b) throws OverFlowException{
if(tope + 1 >= MAX){
throw new OverFlowException();
}

if(tope==-1){
tope = 0;
}

bolitas[tope] = b;
tope++;

b.modPos(tope * 20 + 40, 100);

}
public Bolita desapilar() throws UnderFlowException {
if(tope + 1 <>
throw new UnderFlowException();
}
Bolita c;
tope--;
c = bolitas[tope];

while(c.getX()==-40){
c.modPos(-(tope*20+40),100);
break;
}

return c;
}
}
//CLASE INTERFAZ PILA DE BOLITAS
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
public class InterfazPiladeBolitas extends javax.swing.JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JButton apilar;
private static JPanel panel;
private JButton desapilar;
private PilaDeBolitas p;

private static Graphics g=null;
{
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
}

public void paint(Graphics g) {
super.paint(g);
p.paint(g);
}

/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
InterfazPiladeBolitas inst = new InterfazPiladeBolitas();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}

public InterfazPiladeBolitas() {
super();
initGUI();
p= new PilaDeBolitas();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
apilar = new JButton();
getContentPane().add(apilar);
apilar.setText("Apilar");
apilar.setBounds(56, 230, 167, 43);
apilar.addActionListener(this);
}
{
desapilar = new JButton();
getContentPane().add(desapilar);
desapilar.setText("Desapilar");
desapilar.setBounds(340, 230, 167, 43);
desapilar.addActionListener(this);

}
{
panel = new JPanel();
getContentPane().add(panel);
panel.setBounds(41, 28, 467, 168);
}
pack();
this.setSize(566, 335);
} catch (Exception e) {
e.printStackTrace();
}
}

public void actionPerformed(ActionEvent v) {
if(v.getSource()==apilar){
try{

Bolita b = new Bolita(Color.red, panel);
p.apilar(b);

b.paint(g);
}
catch(PilaDeBolitas.OverFlowException e2){
JOptionPane.showMessageDialog(null, "La pila ya se lleno", "OverFlowException",JOptionPane.WARNING_MESSAGE);
try{
panel.paint(g);
}catch(Exception e){
}
}
}
else if (v.getSource()==desapilar) {
try{
Bolita r = p.desapilar();
r.setXORMode(g);
}
catch(Exception e2){
JOptionPane.showMessageDialog(null, "La pila esta vacia", "OverFlowException",JOptionPane.WARNING_MESSAGE);
try{
panel.repaint();
}catch(Exception e){
}
}
}
}
}