/home/blaster [ Blaster's blog ]

java,programacion,codigos,programas,como programar,netbeans,manual netbeans,bajar netbeans,java,jdk,jdbc

Archive for the ‘Java’ Category

Que son Árboles Binarios de Búsqueda en Java y para que sirven ?

Martes, Abril 15th, 2008

En estos días he tenido la necesidad de ver ciertas operaciones que se implementan el los árboles binarios de búsqueda (Binary Search Trees), y en este sitio encontré una implementación particularmente interesante, espero que les sea de utilidad.

En ciencias de la computación, un árbol binario de búsqueda es un árbol que tiene las siguientes propiedades:

  • Cada nodo tiene un valor
  • Se define un orden total sobre esos valores
  • El subárbol izquierdo de un nodo contiene valores menores o iguales que el valor de dicho nodo.
  • El subárbol derecho de un nodo contiene valores mayores o iguales que el valor de dicho nodo.

La ventaja más notable de los árboles binarios de búsqueda es que los algoritmos de ordenación y búsqueda relacionados como transversal inorden pueden ser muy eficientes.

Los árboles binarios de búsqueda son una estructura de datos fundamental usada para construir más estructuras de datos abstractas como conjuntos y arrays asociativos.
// BinarySearchTree class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x ) –> Insert x
// void remove( x ) –> Remove x
// void removeMin( ) –> Remove minimum item
// Comparable find( x ) –> Return item that matches x
// Comparable findMin( ) –> Return smallest item
// Comparable findMax( ) –> Return largest item
// boolean isEmpty( ) –> Return true if empty; else false
// void makeEmpty( ) –> Remove all items
// ******************ERRORS********************************
// Exceptions are thrown by insert, remove, and removeMin if warranted

/**
* Implements an unbalanced binary search tree.
* Note that all “matching” is based on the compareTo method.
* @author Mark Allen Weiss
*/
public class BinarySearchTree {
/**
* Construct the tree.
*/
public BinarySearchTree( ) {
root = null;
}

/**
* Insert into the tree.
* @param x the item to insert.
* @throws DuplicateItemException if x is already present.
*/
public void insert( Comparable x ) {
root = insert( x, root );
}

/**
* Remove from the tree..
* @param x the item to remove.
* @throws ItemNotFoundException if x is not found.
*/
public void remove( Comparable x ) {
root = remove( x, root );
}

/**
* Remove minimum item from the tree.
* @throws ItemNotFoundException if tree is empty.
*/
public void removeMin( ) {
root = removeMin( root );
}

/**
* Find the smallest item in the tree.
* @return smallest item or null if empty.
*/
public Comparable findMin( ) {
return elementAt( findMin( root ) );
}

/**
* Find the largest item in the tree.
* @return the largest item or null if empty.
*/

public Comparable findMax( ) {
return elementAt( findMax( root ) );
}

/**
* Find an item in the tree.
* @param x the item to search for.
* @return the matching item or null if not found.
*/
public Comparable find( Comparable x ) {
return elementAt( find( x, root ) );
}

/**
* Make the tree logically empty.
*/
public void makeEmpty( ) {
root = null;
}

/**
* Test if the tree is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( ) {
return root == null;
}

/**
* Internal method to get element field.
* @param t the node.
* @return the element field or null if t is null.
*/
private Comparable elementAt( BinaryNode t ) {
return t == null ? null : t.element;
}

/**
* Internal method to insert into a subtree.
* @param x the item to insert.
* @param t the node that roots the tree.
* @return the new root.
* @throws DuplicateItemException if x is already present.
*/
protected BinaryNode insert( Comparable x, BinaryNode t ) {
if( t == null )
t = new BinaryNode( x );
else if( x.compareTo( t.element ) < 0 )
t.left = insert( x, t.left );
else if( x.compareTo( t.element ) > 0 )
t.right = insert( x, t.right );
else
throw new DuplicateItemException( x.toString( ) ); // Duplicate
return t;
}

/**
* Internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the tree.
* @return the new root.
* @throws ItemNotFoundException if x is not found.
*/
protected BinaryNode remove( Comparable x, BinaryNode t ) {
if( t == null )
throw new ItemNotFoundException( x.toString( ) );
if( x.compareTo( t.element ) < 0 )
t.left = remove( x, t.left );
else if( x.compareTo( t.element ) > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.element = findMin( t.right ).element;
t.right = removeMin( t.right );
} else
t = ( t.left != null ) ? t.left : t.right;
return t;
}

/**
* Internal method to remove minimum item from a subtree.
* @param t the node that roots the tree.
*@return the new root.
* @throws ItemNotFoundException if x is not found.
*/
protected BinaryNode removeMin( BinaryNode t ) {
if( t == null )
throw new ItemNotFoundException( );
else if( t.left != null ) {
t.left = removeMin( t.left );
return t;
} else
return t.right;
}

/**
* Internal method to find the smallest item in a subtree.
* @param t the node that roots the tree.
* @return node containing the smallest item.
*/
protected BinaryNode findMin( BinaryNode t ) {
if( t != null )
while( t.left != null )
t = t.left;

return t;
}

/**
* Internal method to find the largest item in a subtree.
* @param t the node that roots the tree.
* @return node containing the largest item.
*/
private BinaryNode findMax( BinaryNode t ) {
if( t != null )
while( t.right != null )
t = t.right;

return t;
}

/**
* Internal method to find an item in a subtree.
* @param x is item to search for.
* @param t the node that roots the tree.
* @return node containing the matched item.
*/
private BinaryNode find( Comparable x, BinaryNode t ) {
while( t != null ) {
if( x.compareTo( t.element ) < 0 )
t = t.left;
else if( x.compareTo( t.element ) > 0 )
t = t.right;
else
return t; // Match
}

return null; // Not found
}

/** The tree root. */
protected BinaryNode root;

// Test program
public static void main( String [ ] args ) {
BinarySearchTree t = new BinarySearchTree( );
final int NUMS = 4000;
final int GAP = 37;

System.out.println( “Checking… (no more output means success)” );

for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS )
t.insert( new Integer( i ) );

for( int i = 1; i < NUMS; i+= 2 )
t.remove( new Integer( i ) );

if( ((Integer)(t.findMin( ))).intValue( ) != 2 ||
((Integer)(t.findMax( ))).intValue( ) != NUMS - 2 )
System.out.println( “FindMin or FindMax error!” );

for( int i = 2; i < NUMS; i+=2 )
if( ((Integer)(t.find( new Integer( i ) ))).intValue( ) != i )
System.out.println( “Find error1!” );

for( int i = 1; i < NUMS; i+=2 ) {
if( t.find( new Integer( i ) ) != null )
System.out.println( “Find error2!” );
}
}
}

// Basic node stored in unbalanced binary search trees
// Note that this class is not accessible outside
// of this package.

class BinaryNode {
// Constructors
BinaryNode( Comparable theElement ) {
element = theElement;
left = right = null;
}

// Friendly data; accessible by other package routines
Comparable element; // The data in the node
BinaryNode left; // Left child
BinaryNode right; // Right child
}

/**
* Exception class for duplicate item errors
* in search tree insertions.
* @author Mark Allen Weiss
*/
public class DuplicateItemException extends RuntimeException {
/**
* Construct this exception object.
*/
public DuplicateItemException( ) {
super( );
}
/**
* Construct this exception object.
* @param message the error message.
*/
public DuplicateItemException( String message ) {
super( message );
}
}

/**
* Exception class for failed finds/removes in search
* trees, hash tables, and list and tree iterators.
* @author Mark Allen Weiss
*/
public class ItemNotFoundException extends RuntimeException {
/**
* Construct this exception object.
*/
public ItemNotFoundException( ) {
super( );
}

/**
* Construct this exception object.
* @param message the error message.
*/
public ItemNotFoundException( String message ) {
super( message );
}
}

Fuente: Java-Tips.org, http://www.java-tips.org/java-se-tips/java.lang/binary-search-tree-implementation-in-java.htm

Java Listas doblemente enlazadas.

Sábado, Abril 5th, 2008

El TDA lista doblemente enlazada, al igual que la lista enlazada, es un TDA dinámico lineal pero, a diferencia de este, cada nodo de la lista doblemente enlazada contiene dos punteros, de forma que uno apunta al siguiente nodo y el otro al predecesor. Esta característica, permite que se pueda recorrer la lista en ambos sentidos, cosa que no es posible en las listas simples.

La declaración del tipo lista doblemente enlazada de enteros es la siguiente:

    struct lista_doble {
gint dato;
lista_doble *siguiente;
lista_doble *anterior;
};
  1. Representa el dato a almacenar, que puede ser de cualquier tipo. En este ejemplo se trataría de una lista de enteros.
  2. Se trata de un puntero al siguiente elemento de la lista. Con este puntero se enlaza con el sucesor, de forma que podamos construir la lista.
  3. Es un puntero al elemento anterior de la lista. Este puntero enlaza con el elemento predecesor de la lista y permite recorrerla en sentido inverso.

Sobre este TDA se definen los mismos operadores básicos que en las listas simples.

Generar archivo distribuible JAR en Netbeans

Jueves, Marzo 20th, 2008

Presionar Mayusculas+F11

o en el menu Build escojes Clean and Build Main Project

en tu carpeta de proyecto se creará una carpeta de nombre dist en la cual se coloca el archivo jar que seria el ejecutable de tu aplicacion.

si usas librerias externas debes modificar el archivo de manifiesto (MANIFEST.MF) que se encuentra dentro del jar. eso lo puedes hacer con winrar

Como Acceder a una base de datos SQLite con Java

Jueves, Marzo 20th, 2008

En este pequeño tutorial explicaré la forma de conectar a una base de datos SQLite desde Netbeans con Java.

El primer paso es bajarse el driver JDBC del SQLite de esta pagina web (bajen el que no diga nativo, sino el que esta hecho para Java en general: Nested JVM)

http://www.zentus.com/sqlitejdbc/

Luego instalen en driver dentro del Netbeans (con este paso tambien pueden instalar drivers para MySQL o Postgres)

Vayan al menu “Tools”, “Library Manager”

En la ventana que les aparece elijan “Add Library”

En el nombre que le pongan pueden poner cualquier cosa, en mi caso yo puse “SQLite”

Una vez creada la libreria, hay que añadir el driver.

Con la libreria seleccionada vayan a la derecha y elijan “Add JAR/Folder” y busquen el archivo JAR del driver.

Luego pongan aceptar.

Ahora ya pueden crear un proyecto en Netbeans que tenga acceso a una base de datos SQLite. Sin embargo para que tu proyecto puede usar de la libreria que has creado, tienes que en el Administrador de Proyecto (la pestaña donde dice Project), ir a la carpeta Libraries y hacer click derecho.

En el menu que aparece elije “Add Library” y añades la libreria SQLite que acabas de crear.

Con eso ya podras crear aplicaciones con acceso a SQLite:

Aqui les pongo de ejemplo un programa en Java:

import java.sql.*;

public class Test {
public static void main(String[] args) throws Exception {
Class.forName(”org.sqlite.JDBC”);
Connection conn = DriverManager.getConnection(”jdbc:sqlite:test.db”);
Statement stat = conn.createStatement();
stat.executeUpdate(”create table people (name, occupation);”);
stat.executeUpdate(”insert into people values (’Gandhi’, ‘politics’);”);
stat.executeUpdate(”insert into people values (’Turing’, ‘computers’);”);
stat.executeUpdate(”insert into people values (’Wittgenstein’, ’smartypants’);”);

ResultSet rs = stat.executeQuery(”select * from people;”);
while (rs.next()) {
System.out.println(”name = ” + rs.getString(”name”));
System.out.println(”occupation = ” + rs.getString(”occupation”));
}
rs.close();
conn.close();
}
}

Como Ejecutar un comando de Linux desde Java

Jueves, Marzo 20th, 2008

Tomado de:

http://javihm77.blogspot.com/search/label/Linux

Para escribir un comando de consola de linux desde java necesitamos el siguiente codigo:

try
{
String command;
command=”ls”;
//command=”mount -h”;
final Process process = Runtime.getRuntime().exec(command);
new Thread(){
public void run(){
try{
InputStream is = process.getInputStream();
byte[] buffer = new byte[1024];
for(int count = 0; (count = is.read(buffer)) >= 0;){
System.out.write(buffer, 0, count);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
try{
InputStream is = process.getErrorStream();
byte[] buffer = new byte[1024];
for(int count = 0; (count = is.read(buffer)) >= 0;){
System.err.write(buffer, 0, count);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}.start();

int returnCode = process.waitFor();
System.out.println(”Return code = ” + returnCode);
}
catch (Exception e){
e.printStackTrace();
}

Un thread nos tira los errores y el otro lo que devuelve al ejecutar el comando.
En un string ponemos comandos con espacios. Para mayor referencia visitar: