Saturday, June 25, 2005

Problemas C, F y G


/*
* Created on 06/25/2005
*
* Esta clase fue probada con JUNIT, usando TDD
* Si desea ver los test, dejar un comentario
*/
package estructura.examen;

/**
* @author vns
*
*/
public class ManejoString {

/**
*
*/
public ManejoString() {
super();
}

/**
* F) Busca un substring en un string dado
*
* @param string
* @param retorno
* @param i
* @param len
*/
public static void subStr(String string, String r, int ind, int len) {
//TODO terminar test
for (int i = ind ; i < ind + len; i++) {
r = r + string.charAt(i);
}
}

/**
* G) Busca la posicion de una Subcadena dentro de otra,
* y si no se encuentra retorna 0
*
* @param string
* @param substring
*/
public static int find(String string, String substring) {
int cont = 0;

//primera manera de hacerlo
/*for (int i = 0; i < string.length(); i++) {
if ( string.charAt(i) == substring.charAt(0) )
for (int j = 0, pos = i; j < substring.length(); j++, pos++){
if ( string.charAt(pos) == substring.charAt(j) ){
cont++;
}else{
cont = 0;
break;
}

if (cont == substring.length()) {
return i;
}
}
}*/

// Segunda manera de hacerlo
for (int j = 0, pos = j; j < string.length(); j++){
if ( string.charAt(j) == substring.charAt(pos) ){
pos++;
cont++;
}else{
pos = 0;
cont = 0;
continue;
}

if ( cont == substring.length()) {
return j - cont + 1;
}
}
return 0;
}

/**
* C) Función length usando for
*
* @param string
* @return
*/
public static int lentghWithFor(String string) {

int i = 0;
for (;;) {
try {
string.charAt(i);
i++;
} catch (StringIndexOutOfBoundsException e) {
return i;
}
}
}

/**
* C) Función length usando While
*
* @param string
* @return
*/
public static int lentghWithWhile(String string) {
int i = 0;
while(true) {
try {
string.charAt(i);
i++;
} catch (StringIndexOutOfBoundsException e) {
return i;
}
}
}

}

Wednesday, June 22, 2005

Problema Estructura

/*
* Created on 06/18/2005
*
* Manejo de estructuras y indices. Dado el ejemplo de una base de datos
*
* a) Los ordena segun el valor de uno de los campos elegidos
* b) Crear un indice para la busqueda a partir de un campo elegido
*/
package estructura;

import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Vector;

/**
* @author vns
*
*/
public class Estructura {

/**
*
*/
public Estructura() {
super();
}

public static void main(String[] args) {

}
}

class Persona {
private String pNombre;
private String pApellido;
private int edad;

/**
* @param nombre
* @param apellido
* @param edad
*/
public Persona(String nombre, String apellido, int edad) {
super();
pNombre = nombre;
pApellido = apellido;
this.edad = edad;
}

/**
*
*/
public Persona() {
}

/**
* @return Returns the pApellido.
*/
public String getPApellido() {
return pApellido;
}

/**
* @param apellido The pApellido to set.
*/
public void setPApellido(String apellido) {
pApellido = apellido;
}

/**
* @return Returns the pNombre.
*/
public String getPNombre() {
return pNombre;
}

/**
* @param nombre The pNombre to set.
*/
public void setPNombre(String nombre) {
pNombre = nombre;
}

/**
* @return Returns the edad.
*/
public int getEdad() {
return edad;
}

/**
* @param edad The edad to set.
*/
public void setEdad(int edad) {
this.edad = edad;
}

/*
* Display the persona
*/
public String print() {

return pNombre + " " + pApellido + " " + edad;
}

}

class HighArrayPersona
{
private Persona[] a;
private int nElems;
LinkedList index = new LinkedList();

public HighArrayPersona(int max)
{
a = new Persona[max];
nElems = 0;
}

public boolean find(String searchKey)
{
int j;
for(j=0; j < nElems; j++)
if(a[j].getPNombre().toString() == searchKey)
break;
if(j == nElems)
return false;
else
return true;
}

public void insert(Persona value)
{
a[nElems] = value;
nElems++;
}

public boolean delete(Persona value)
{
int j;
for(j=0; j < nElems; j++)
if( value == a[j] )
break;
if(j==nElems)
return false;
else
{
for(int k=j; k < nElems; k++)
a[k] = a[k+1];
nElems--;
return true;
}
}

public void display()
{
for(int j=0; j < nElems; j++)
a[j].print();
System.out.println("");
}
//----------------------------------------------------------
// sort elements
public void sort(String field){
Object sample = new Persona();
FieldComparator fieldComparator = new FieldComparator(sample, field);
int i;

for (i = 0; i < nElems; i++)
for (int j = 0; j < nElems; j++)
if ( fieldComparator.compare(a[i],a[j]) <= -1 )
swap(i,j);
}

// create the index for a field
public void createindex(String fields){
for(int i=0; i < nElems; i++)
if ( a[i] != null )
index.add( i, FieldComparator.getField(a[i],fields) ); // add all field of the objects
}

// changes the position i --> j
private void swap(int i, int j){
Persona temp = a[i];
a[i] = a[j];
a[j] = temp;
}

// delete duplicates
public void noDups()
{
int j;
for(j=0; j < nElems; j++) // look for it
for (int i = j; i < nElems; i++)
if( (a[j] == a[i]) && (i != j) && (a[j] != null) && (a[i] != null) )
a[i] = null;

if (j == nElems) // can't find it
return;

for(int k=0; k < nElems; k++){
if ( a[k] == null )
delete(a[k]); // delete all -1 value
}
} // end noDups()
//----------------------------------------------------------

} // end class HighArray

class FieldComparator implements Comparator{

Field[] publicField;
Vector fieldVec;
String SortBY;
boolean nameMatch = true;

/**
*
*/
public FieldComparator() {
super();
}


/**
* @param sample
* @param sortBY
*/
public FieldComparator(Object sample, String sortBY) {
SortBY = sortBY;
Class c = sample.getClass();
fieldVec = new Vector();
//TODO check for SecurityException don't apper
publicField = c.getFields();
for (int i = 0; i < publicField.length; i++) {
fieldVec.add( publicField[i].getName() );
}

nameMatch = fieldVec.contains(sortBY);
}// End constructor


/**
* @return Returns the sortBY.
*/
public String getSortBY() {
return SortBY;
}

/**
* @param sortBY The sortBY to set.
*/
public void setSortBY(String sortBY) {
SortBY = sortBY;
}

/**
* You should set the field to compared, set SortBY or in the constructor
*
* @param the objects to compared, arg0 and arg1
*
* @return the value 0 if the argument Object is equal to this Object;
* a value less than 0 if this Object is lexicographically less than the Object argument;
* and a value greater than 0 if this Object is lexicographically greater than the Object argument.
*/
public int compare(Object arg0, Object arg1) {

String str0 = getField(arg0, getSortBY());
String str1 = getField(arg1, getSortBY());

return str0.compareTo(str1);
}

static public String getField(Object obj, String field){
Class c = obj.getClass();
String string = "";

try {
// TODO check for SecurityException don't apper
Field field0 = c.getField( field );

string = (String)field0.get(obj);

} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return string;
}
}

Tuesday, June 21, 2005

Problema libro de Robert Lafore

Problema #6 - pág. 76
Data Structures and Algorithms in Java (2nd Edition)

by Robert Lafore

HighArrayApp.java
===========================
/*
* Created on 06/20/2005
*
* Problema #6 - pág. 76
* Data Structures and Algorithms in Java (2nd Edition)
* by Robert Lafore
*
* Descripcion:
* 2.6 write a noDups() method for the HighArray class
* of the highArray.java program (Listing 2.3). This method should
* remove all duplicates from the array. That is, if three items
* with the key 17 appear in the array, noDups() should remove two of them.
* Don't worry about maintaining the order of the items. One approach
* is to first compare every item with all the other items and overwrite
* any duplicates with a null (or a distinctive value that ins't used for
* real keys). Then remove all the nulls. Of course, the array size
* will be reduced.
*/
package estructura;

/**
* @author vns
*
*/

//highArray.java
//demonstrates array class with high-level interface
//to run this program: C>java HighArrayApp

////////////////////////////////////////////////////////////////
class HighArray
{
private double[] a; // ref to array a
private int nElems; // number of data items
//----------------------------------------------------------

public HighArray(int max) // constructor
{
a = new double[max]; // create the array
nElems = 0; // no items yet
}
//----------------------------------------------------------

public boolean find(double searchKey)
{ // find specified value
int j;
for(j=0; j < nElems; j++) // for each element,
if(a[j] == searchKey) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return false; // yes, can't find it
else
return true; // no, found it
} // end find()
//----------------------------------------------------------

public void insert(double value) // put element into array
{
a[nElems] = value; // insert it
nElems++; // increment size
}
//----------------------------------------------------------

public boolean delete(double value)
{
int j;
for(j=0; j < nElems; j++) // look for it
if( value == a[j] )
break;
if(j==nElems) // can't find it
return false;
else // found it
{
for(int k=j; k < nElems; k++) // move higher ones down
a[k] = a[k+1];
nElems--; // decrement size
return true;
}
} // end delete()
//----------------------------------------------------------

public void display() // displays array contents
{
for(int j=0; j < nElems; j++) // for each element,
System.out.print(a[j] + " "); // display it
System.out.println("");
}
//----------------------------------------------------------

public void noDups()
{
int j;
for(j=0; j < nElems; j++) // look for it
for (int i = j; i < nElems; i++)
if( (a[j] == a[i]) && (i != j) && (a[j] != -1) && (a[i] != -1) )
a[i] = -1;

if (j == nElems) // can't find it
return;

for(int k=0; k < nElems; k++){
if ( a[k] == -1 )
delete(a[k]); // delete all -1 value
}
} // end noDups()
//----------------------------------------------------------

} // end class HighArray
////////////////////////////////////////////////////////////////
class HighArrayApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
HighArray arr; // reference to array
arr = new HighArray(maxSize); // create the array
arr.insert(77); // insert 10 items
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);
arr.display(); // display items
int searchKey = 35; // search for item
if( arr.find(searchKey) )
System.out.println("Found " + searchKey);
else
System.out.println("Can't find " + searchKey);
arr.delete(00); // delete 3 items
arr.delete(55);
arr.delete(99);
arr.display(); // display items again
} // end main()
} // end class HighArrayApp

Sunday, June 19, 2005

This is the Grammar of DUDU+


/*
* DUDU+ codename MiniJava
* HECHO... in Dominican Republic
* author vns
*/


options{
LOOKAHEAD = 1;
STATIC = false;
JAVA_UNICODE_ESCAPE = true;
}

PARSER_BEGIN(MiniJava)

import java.util.*;

public class MiniJava {

public static void main(String[] args) throws ParseException, TokenMgrError {

MiniJava parser;
String file = null;
long time = 0;
long parseTime = 0;
long startTime = 0;

if (args.length == 0)
{
System.out.println("Error messages...");
return;

} else if ( args.length == 1 ){
file = args[0];
System.out.println("Start parsing...");

try
{
parser = new MiniJava(new java.io.FileInputStream(file));

} catch ( java.io.FileNotFoundException e ) {

System.out.println("Parser error: Filename " + file + " not found." );
return;
}
} else {
System.out.println("Debe escribir: java MiniJava inputfile");
return;
}
try
{
startTime = System.currentTimeMillis();
parser.Start();
parseTime = System.currentTimeMillis();
time = parseTime - startTime;

System.out.println(" Time of parsing: " + time + " ms");
System.out.println(" DuDu successfully end");

} catch ( ParseException pex) {

System.out.println( pex.getMessage() );
System.out.println(" ParserException during parse file" );
}
}/* main method*/
}

PARSER_END(MiniJava)

/* Eat white space and comment*/
SKIP : {
" "
| "\t"
| "\n"
| "\r"
| <"//" (~["\n","\r"])* ("\n" | "\r" | "\r\n")>
| <"/*" (~["*"])* "*" ("*" | ~["*","/"] (~["*"])* "*")* "/">
}

TOKEN : /* RESERVED WORDS AND LITERALS */
{
< BOOLEAN: "boolean" >
| < BYTE: "byte" >
| < CHAR: "char" >
| < CLASS: "class" >
| < DOUBLE: "double" >
| < FALSE: "false" >
| < FLOAT: "float" >
| < FINAL: "final" >
| < INT: "int" >
| < LONG: "long" >
| < PUBLIC: "public" >
| < SHORT: "short" >
| < STATIC: "static" >
| < TRUE: "true" >
| < VOID: "void" >
| < NEW: "new" >
| < MAKE: "make" >
| < STACK: "stack" >
| < REPEAT: "repeat" >
| < UNTIL: "until" >
| < ADDSTACK: "addStack" >
| < ORDSTACK: "ordStack" >
| < ASCENDENTE: "ascendente" >
| < DESCENDENTE: "descendente" >

}

TOKEN : /* SEPARATORS */
{
< LPAREN: "(" >
| < RPAREN: ")" >
| < LBRACE: "{" >
| < RBRACE: "}" >
| < LBRACKET: "[" >
| < RBRACKET: "]" >
| < SEMICOLON: ";" >
| < COMMA: "," >
}

TOKEN : /* OPERATORS */
{
< ASSIGN: "=" >
| < INCR: "++" >
| < DECR: "--" >
| < PLUS: "+" >
| < MINUS: "-" >
| < STAR: "*" >
| < SLASH: "/" >

}

TOKEN : /* LITERALS */
{
< INTEGER_LITERAL:
< DECIMAL_LITERAL > (["l","L"])?
>
|
< #DECIMAL_LITERAL: ["0"-"9"] (["0"-"9"])* >
|
< FLOATING_POINT_LITERAL:
(["0"-"9"])+ "." (["0"-"9"])* ( < EXPONENT > )? (["f","F","d","D"])?
| "." (["0"-"9"])+ ( < EXPONENT >)? (["f","F","d","D"])?
| (["0"-"9"])+ < EXPONENT > (["f","F","d","D"])?
| (["0"-"9"])+ (< EXPONENT >)? ["f","F","d","D"]
>
|
< #EXPONENT: ["e","E"] (["+","-"])? (["0"-"9"])+ >
|
< CHARACTER_LITERAL:
"'"
( (~["'","\\","\n","\r"])
| ("\\"
( ["n","t","b","r","f","\\","'","\""]
| ["0"-"7"] ( ["0"-"7"] )?
| ["0"-"3"] ["0"-"7"] ["0"-"7"]
)
)
)
"'"
>
|
< STRING_LITERAL:
"\""
( (~["\"","\\","\n","\r"])
| ("\\"
( ["n","t","b","r","f","\\","'","\""]
| ["0"-"7"] ( ["0"-"7"] )?
| ["0"-"3"] ["0"-"7"] ["0"-"7"]
)
)
)*
"\""
>
}

TOKEN : {
< IDENTIFIER: < LETTER > ( < LETTER > | < DIGIT > )*>
| <#LETTER: ["$","A"-"Z","_","a"-"z"]>
| <#DIGIT: ["0"-"9"]>
}


/*********************************************
* THE MINIJAVA LANGUAGE GRAMMAR STARTS HERE *
*********************************************/

/*
* Struts.
*/

void Start() throws ParseException :
{}
{
(TypeDeclaration() )*
}


void TypeDeclaration() :
{}
{
ClassDeclaration()
}

/*
* Declaracion de clases
*/
void ClassDeclaration() :
{}
{
( "final" | "public" | "static" )* "class" < IDENTIFIER >
"{" ( ClassBodyDeclaration() )* "}"

}

void ClassBodyDeclaration() :
{}
{
LOOKAHEAD(2)
FieldDeclaration()
|
Statement()
}

void FieldDeclaration() :
{}
{
( "public" | "static" | "final" )*
Type() VariableDeclarator() ( "," VariableDeclarator() )* ";"

}

void VariableDeclarator() :
{}
{
VariableDeclaratorId() [ "=" VariableInitializer() ]
}

void VariableDeclaratorId() :
{}
{
< IDENTIFIER > ( "[" "]" )*
}

void VariableInitializer() :
{}
{
ArrayInitializer()
|
Expression()

}

void ArrayInitializer() :
{}
{
"{" [ VariableInitializer() ( LOOKAHEAD(2) "," VariableInitializer() )* ] [ "," ] "}"
}

/*
* Tipos, nombre y sentencias
*/
void Type() :
{}
{
PrimitiveType() ( "[" "]" )*
}

void PrimitiveType() :
{}
{
"boolean"
|
"char"
|
"byte"
|
"short"
|
"int"
|
"long"
|
"float"
|
"double"
}

void Name() :
{ }
{
< IDENTIFIER >
}

/*
* Expression syntax
*/

void Expression() :
{}
{
ConditionalExpression() [ AssignmentOperator() AdditiveExpression() ]
}

void AssignmentOperator() :
{}
{
"="
}

void ConditionalExpression() :
{}
{
ConditionalOrExpression() [ "?" Expression() ":" ConditionalExpression() ]
}

void ConditionalOrExpression() :
{}
{
ConditionalAndExpression() ( "||" ConditionalAndExpression() )*

}

void ConditionalAndExpression() :
{}
{
EqualityExpression() ( "&&" EqualityExpression() )*

}

void EqualityExpression() :
{}
{
RelationalExpression() ( ( "==" | "!=" ) RelationalExpression() )*

}

void RelationalExpression() :
{}
{
AdditiveExpression() ( ( "<" | ">" | "<=" | ">=" ) AdditiveExpression() )*

}

void AdditiveExpression() :
{}
{
MultiplicativeExpression() ( LOOKAHEAD(2)( "+" | "-" ) MultiplicativeExpression() )*

}

void MultiplicativeExpression() :
{}
{
UnaryExpression() ( ( "*" | "/" ) UnaryExpression() )*

}

void UnaryExpression() :
{}
{
( "+" | "-" ) UnaryExpression()
|
UnaryExpressionNotPlusMinus()
}

void UnaryExpressionNotPlusMinus() :
{}
{
PostfixExpression()
}

void PostfixExpression() :
{}
{
PrimaryExpression() [ "++" | "--" ]
}

void PrimaryExpression() :
{}
{
PrimaryPrefix() ( PrimarySuffix() )*
}

void PrimaryPrefix() :
{}
{
Literal()
|
"(" Expression() ")"
|
AllocationExpression()
|
Name()
}

void PrimarySuffix() :
{}
{
"[" Expression() "]"
|
LOOKAHEAD(2)
"." "addStack" "(" ( Name() | Literal() ) ")"
|
"." "ordStack" "(" OrdenType() ")"

}

void OrdenType() :
{}
{
"ascendente"
|
"descendente"
}

void Literal() :
{}
{
< INTEGER_LITERAL >
|
< FLOATING_POINT_LITERAL >
|
< CHARACTER_LITERAL >
|
< STRING_LITERAL >
|
BooleanLiteral()
}

void BooleanLiteral() :
{}
{
"true"
|
"false"
}

void AllocationExpression() :
{}
{
"new" PrimitiveType() ArrayDimsAndInits()
|
MakeStack()
}

void MakeStack() :
{}
{
"make" "stack"
}

void ArrayDimsAndInits() :
{}
{
LOOKAHEAD(2)
( LOOKAHEAD(2) "[" Expression() "]" )+ ( LOOKAHEAD(2) "[" "]" )*
|
( "[" "]" )+ ArrayInitializer()
}

void Statement() :
{}
{
Expression() ";"
|
RepeatStatement()

}

void RepeatStatement() :
{}
{
"repeat" Statement() "until" "(" Expression() ")"

}