Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

“AÑO DE LA UNIVERSALIZACIÓN DE LA SALUD”

UNIVERSIDAD NACIONAL DE CAJAMARCA

FACULTAD DE INGENIERÍA

ESCUELA ACADÉMICO PROFESIONAL INGENIERÍA DE SISTEMAS

ESTUDIANTE: TAFUR VALDIVIA, ROBERTO JHULIÑO

CURSO: ALGORITMOS Y ESTRUCTURA DE DATOS 2

DOCENTE: MALPICA RODRIGUEZ MANUEL ENRIQUE

TEMA: LISTAS ENLAZADAS DOBLES Y CIRCULARES

GRUPO: B

CAJAMARCA-PERÚ
Ejercicio 1
Código Java
- Clase Nodo
package comparacionColas;

public class Nodo <T> {

private T value;
private Nodo<T> next;

public Nodo(T value, Nodo<T> next) {


this.value = value;
this.next = next;
}

public Nodo(T value) {


this.value = value;
this.next = null;
}

public T getValue() {
return value;
}

public void setValue(T value) {


this.value = value;
}

public Nodo<T> getNext() {


return next;
}

public void setNext(Nodo<T> next) {


this.next = next;
}

@Override
public String toString() {

return value.toString();
}
}

- Clase ListaEnlazada
package comparacionColas;

public class ListaEnlazada<T> {

protected Nodo<T> first;


private Nodo<T> end;
private int length;

public ListaEnlazada() {
first = null;
end = null;
length = 0;
}

public Nodo<T> getFirst() {


return first;
}

public void setFirst(Nodo<T> first) {


this.first = first;
}

public Nodo<T> getEnd() {


return end;
}

public void setEnd(Nodo<T> end) {


this.end = end;
}

public int getLength() {


return length;
}

public void setLength(int length) {


this.length = length;
}

public void addHail(T value) {


first = new Nodo<T>(value);
if(isEmtpty()) {
end = first;
}
}

public boolean isEmtpty() {


return end == null || length == 0;
}

public void addTail(T dato) {


if(first == null) {
first = end = new Nodo<T>(dato);
}else {
end.setNext(new Nodo<T>(dato));
end = end.getNext();
}
length++;
}

public T deleteHeat() {
T element = null;
if(!isEmtpty()) {
if(first == end) {
element = first.getValue();
first = end = null;
}else {
element = first.getValue();
first = first.getNext();
}
length--;
}else {
System.out.println("Sorry, the list is empty!!!");
}

return element;
}
/*
public Curso eliminarFin() {

if(end == null) {
System.out.println("La lista está vacía");
return null;
}
Curso curso = end.getDato();
if(end == first) {
end = first = null;
}else {
Nodo temp = first;
while (temp.getSiguiente() != end) {
temp = temp.getSiguiente();
}
temp.setSiguiente(null);
end = temp;
}
return curso;
}
*/
@Override
public String toString() {
String s = "[";
if(!isEmtpty()) {
Nodo<T> aux = first;
while(aux != null) {
s += aux.getValue() + ", ";
aux = aux.getNext();
}
s = s.substring(0,s.length() - 2);
}

s += "]";
return s;
}

- Clase cola
package comparacionColas;

public class Cola<T> extends ListaEnlazada<T>{

public Cola() {
super();
}

public void enqueue(T value) {


super.addTail(value);
}

public T dequeue() {
return super.deleteHeat();
}

@Override
public String toString() {
String s = "[";
if(!isEmtpty()) {
Nodo<T> aux = super.first;
while(aux != null) {
s += aux.getValue() + ", ";
aux = aux.getNext();
}
s = s.substring(0,s.length() - 2);
}

s += "]";
return s;
}
}

- Clase Persona
package comparacionColas;

public class Persona {

String transaction;
int timeSeconds;

public Persona(String transaction, int timeSeconds) {


this.transaction = transaction;
this.timeSeconds = timeSeconds;
}

@Override
public String toString() {

return transaction +"[" + timeSeconds +"]";


}
}

- Clase prueba
package comparacionColas;

import java.util.Random;

public class Prueba {

public static void main(String[] args) {


System.out.println("\t\tThe Bank");

int time1 = 0, time2 = 0;


Random r = new Random();

int sizeClients = r.nextInt(21) + 1;


for(int k = 0; k < 10 ; k++) {

Cola<Persona> queue = new Cola<>();


for(int i = 0; i < sizeClients; i++) {
int trans = r.nextInt(4);
int time = r.nextInt(151) + 30;
if(trans == 0) {
queue.enqueue(new Persona("Transferencia", time));
}
if(trans == 1) {
queue.enqueue(new Persona("Retiro", time));
}
if(trans == 2) {
queue.enqueue(new Persona("Depósito", time));
}
if(trans == 3) {
queue.enqueue(new Persona("Giro", time));
}
}

System.out.println("\f First case:");


System.out.println(queue.toString());
System.out.println("Size: " + queue.getLength());
Cola<Persona> queue1 = new Cola<>(), queue2 = new Cola<>(), queue3 = new
Cola<>();
int t1 = 0,t2 = 0,t3 = 0;
for(int i = 0; i < sizeClients; i++) {
Persona aux = queue.dequeue();
int t = lessTime(t1,t2,t3);
if(t == 1) {
t1 += 5 + aux.timeSeconds;
queue1.enqueue(aux);
}
if(t == 2) {
t2 += 5 + aux.timeSeconds;
queue2.enqueue(aux);
}
if(t == 3) {
t3 += 5 + aux.timeSeconds;
queue3.enqueue(aux);
}
}
System.out.println("Caja 1:" + queue1);
System.out.println("Caja 2:" + queue2);
System.out.println("Caja 3:" + queue3);
System.out.println("..........");
System.out.println("Tiempo total caja 1: " +t1);
System.out.println("Tiempo total caja 2: " +t2);
System.out.println("Tiempo total caja 3: " +t3);

System.out.println("----------------------------------------------------------------------");

for(int i = 0; i < sizeClients; i++) {


int trans = r.nextInt(4);
int time = r.nextInt(151) + 30;
if(trans == 0) {
queue.enqueue(new Persona("Transferencia", time));
}
if(trans == 1) {
queue.enqueue(new Persona("Retiro", time));
}
if(trans == 2) {
queue.enqueue(new Persona("Depósito", time));
}
if(trans == 3) {
queue.enqueue(new Persona("Giro", time));
}
}

System.out.println("\f Second case:");


System.out.println(queue.toString());
System.out.println("Size: " + queue.getLength());
Cola<Persona> queue4 = new Cola<>(), queue5 = new Cola<>(), queue6 = new
Cola<>();
int t4 = 0,t5 = 0,t6 = 0;
while(queue.getLength() != 0) {
if(queue.getLength() != 0) {
Persona aux = queue.dequeue();
queue4.enqueue(aux);
t4 += 5 + aux.timeSeconds;

}
if(queue.getLength() != 0) {
Persona aux = queue.dequeue();
queue5.enqueue(aux);
t5 += 5 + aux.timeSeconds;
}
if(queue.getLength() != 0) {
Persona aux = queue.dequeue();
queue6.enqueue(aux);
t6 += 5 + aux.timeSeconds;
}
}
System.out.println("Caja 1: " + queue4);
System.out.println("Caja 2: " + queue5);
System.out.println("Caja 3: " + queue6);
System.out.println("..............");
System.out.println("Tiempo total caja 1: " + t4);
System.out.println("Tiempo total caja 2: " + t5);
System.out.println("Tiempo total caja 3: " + t6);

System.out.println();
System.out.println("----------------------------------------");
int max1 = max(t1,t2,t3);
time1 += max1;
int max2 = max(t4,t5,t6);
time2 += max2;
System.out.println("The best type is: " + bestQueue(max1, max2));
}

System.out.println("---------------------------------------------------------------");
System.out.println("\n\f Average time in the first queue: " +(time1/21));
System.out.println("\n\f Average time in the second queue: " +(time2/21));

if(time1 < time2) {


System.out.println("\n\fTHE BEST IS THE FIRST");
}
else {
System.out.println("\n\fTHE BEST IS THE SECOND");
}

private static int max(int t1, int t2, int t3) {


int max = t1;
if(t2 > max) {
max = t2;
}
if(t3 > max) {
max = t3;
}
return max;
}

private static String bestQueue(int t1, int t2) {


int min = t1;
if(t2 < min) {
min = t2;
}
if(min == t1 ) {
return "The best is the first case with: " + min;
}else {

return "The best is the second case with: " + min;


}
}

private static int lessTime(int t1, int t2, int t3) {


int less = t1;

if(t2 < less) {


less = t2;
}
if(t3 < less) {
less = t3;
}
if(less == t1) {
return 1;
}
if(less == t2) {
return 2;
}
return 3;
}

Capturas de pantalla de ejecución


Explicación de la solución
- Para poder identificar cual método de formar colas es más efectivo en cuanto al tiempo que tardaría
el banco en atender a todas las personas que asisten, se pone como condición de que en el
experimento como máximo puedan participar 21 personas y como mínimo 1 persona. Además cada
persona puede tardar en realizar un transacción entre 30 y 150 segundos, y también 5 segundos en
pasar a la ventanilla y otra cosa importante es que este experimento se tiene que realizar 10 veces
para sacar un promedio de los tiempos que tardan cada tipo de cola en atender a todos los clientes y
así poder determinar cuál es más efectivo.

- Analizando el funcionamiento de la primera cola : En esta cola se ha creado una cola general (similar a
la cola en el Banco de la Nación en donde hay una cola general hasta estar a unos metros de las
ventanillas), en esta parte se ha considerado que todas las ventanillas están vacías y que la primera
persona que va a ser atendida pasa a la ventanilla 1, y la segunda persona pasa a la ventanilla 2 y la
tercera persona pasa a la ventanilla 3, luego con la cuarta persona se espera hasta que una de las
ventanillas se libere ( una de las tres persona en pasar a las ventanillas va a realizar su transacción en
menos tiempo que los otro dos y se va a retirar ya del banco), entonces luego de encontrar cual fue la
persona que salió ya, la cuarta persona en la cola general pasa a esa ventanilla. Y así sucesivamente
se va repitiendo hasta que se termina de atender a todas las personas de la cola general. Para poder
determinar cuál ha sido el tiempo total del banco en atender a todas las personas, en cada ventanilla
se va registrando el tiempo que tardó en atender desde la primera persona hasta la última, luego de
encontrar los tiempos de las tres ventanillas se determina cuál es el mayor y ese será el tiempo que
tardó el banco en atender a todos sus clientes.

- Analizando el funcionamiento de la segunda cola: En esta cola se intenta simular 3 colas dentro del
banco (en otras palabras podemos decir que cada ventanilla tiene su cola), es como si la primera
persona iría a la cola 1, la segunda persona a la cola 2, la tercera persona a la cola 3, la cuarta persona
a la cola 4, la quinta persona a la cola 5 y así sucesivamente. Si el experimento cuenta con 21
personas, entonces cada ventanilla atendería a 7 personas cada una. En cada ventanilla se registra el
tiempo que tarda en atender a todos los clientes, y luego se evalúa a cada ventanilla para determinar
cuál es el tiempo mayor en atención y este sería el tiempo que tardó el banco en atender a todos sus
clientes. Cabe resaltar que en ambos casos de tipos de colas el tiempo de atención de cada ventanilla
está compuesto por la suma del tiempo de 5 segundos que tarda el cliente en llegar a la ventanilla y
el tiempo de su transacción de todos los clientes que fueron atendidos en dicha ventanilla.

- Finalmente analizamos cual tipo de cola es mejor: Como el experimento consta de repetir 10 veces el
análisis de la cola tipo 1 y de la cola tipo2, entonces en cada vez que se analiza se encuentra el tiempo
de la cola tipo 1 y se guarda ese tiempo en una variable t1 y lo mismo con la cola de tipo 2 se guarda
su tiempo en una variable t2. Ya al finalizar se divide a t1/21 y t2/21 para poder determinar un
promedio del tiempo que tardaría el banco en atender a todos sus clientes con cada tipo de cola.
Y como podemos observar en la prueba el resultado es siempre que el mejor es la cola de tipo1.
En conclusión, se afirma que el banco debería implementar el tipo de cola 1 para poder atender a
todos sus clientes en el menor tiempo posible.

Ejercicio 2
Código Java
- Clase Nodo
package pilasPrefija;

public class Nodo<T> {


private T value;
private Nodo<T> next;

public Nodo(T value) {


this.value = value;
next = null;
}
public Nodo(T value, Nodo<T> next) {
this.value = value;
this.next = next;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Nodo<T> getNext() {
return next;
}
public void setNext(Nodo<T> next) {
this.next = next;
}

@Override
public String toString() {

return value.toString();
}
}

- Clase ListaEnlazada
package pilasPrefija;

public class Lista_Enlazada<T> {

protected Nodo<T> first;


public int length;

public Lista_Enlazada() {
first = null;
length = 0;
}

public Nodo<T> getFirst() {


return first;
}
public void addFirst(T value) {
if(isEmpty()) {
first = new Nodo<T>(value);
}else {
first = new Nodo<T>(value, first);
}

length++;
}

public boolean isEmpty() {


return first == null;
}

public void addEnd(T value) {


Nodo<T> newValue = new Nodo<T>(value);

if(first == null) {
first = newValue;
}
else {
Nodo<T> previuos = first;
while(previuos.getNext() != null) {
previuos = previuos.getNext();
}
previuos.setNext(newValue);
}
length--;

@Override
public String toString() {
String s = "[";
if(!isEmpty()) {
Nodo<T> temp = first;
while(temp != null) {
s += temp.getValue() + ", ";
temp = temp.getNext();
}

s = s.substring(0, s.length() - 2);


}
s += "]";
return s;
}

public T deleteFirst() {
T element = null;
if(!isEmpty()) {
element = first.getValue();
first = first.getNext();
length --;
}

return element;
}

public Object deletePosition(int position) {


Object elemet = null;
if(first == null) {
System.out.println("The list is empty!");
}else if(position == 1) {
elemet = deleteFirst();
}else {
Nodo<T> previuos = first;
for(int i = 1; previuos.getNext() != null && position > 0 ; i++) {
if(i == position - 1) {
elemet = previuos.getNext().getValue();
previuos.setNext(previuos.getNext().getNext());
length --;
return elemet;
}
previuos = previuos.getNext();

}
System.out.println("Invalid position...");
}
return elemet;
}
public Object deleteEnd() {
Object element = null;
if(first == null) {
System.out.println("The list is empty!");
}else if(first.getNext() == null) {
element = deleteFirst();
}else {
Nodo<T> temp = first;
while (temp != null) {
if(temp.getNext().getNext() == null) {
element = temp.getNext();
temp.setNext(null);
break;
}else {
temp = temp.getNext();
}
}
length --;
}
return element;
}

public void emptyList() {


first = null;
}

- Clase Pila
package pilasPrefija;

public class Pila<T> extends Lista_Enlazada<T>{

public Pila() {
super();
}
public void push(T object) {
super.addFirst(object);
}

public T pop() {
return super.deleteFirst();
}

public T peek() {
return super.first.getValue();
}
}

- Clase prueba
package pilasPrefija;

import java.util.Scanner;
public class Prueba {
static Scanner read = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("\t\tInfix to prefix");
System.out.print("Enter your expression: ");
String expression = read.nextLine();
expression = expression.replace(" ", "");
Pila<Character> stack = new Pila<>();

for(int i = 0; i < expression.length(); i++) {


stack.push(expression.charAt(i));
}

Pila<Integer> stackAux = new Pila<>();


Pila<Character> stackPrefix = new Pila<>();

String operators = "-+/*^";

while(!stack.isEmpty()) {
char c = stack.pop();
int index = operators.indexOf(c);

if(index != -1) {
if(stackAux.isEmpty()) {
stackAux.push(index);
}else {
while(!stackAux.isEmpty()) {
int priorityStack = stackAux.peek()/2;
int priorityOperator = index / 2;
if(priorityStack > priorityOperator && c != '^') {

stackPrefix.push(operators.charAt(stackAux.pop()));
}else {
break;
}
}
stackAux.push(index);
}
}else if(c == ')') {
stackAux.push(-2);
}else if(c == '(') {
while(stackAux.peek() != -2) {
stackPrefix.push(operators.charAt(stackAux.pop()));
if(stackAux.isEmpty()) {
break;
}
}
if(!stack.isEmpty()) {
stackAux.pop();
}
}
else {
stackPrefix.push(c);
}
}
while(!stackAux.isEmpty()) {
int i = stackAux.pop();
if(i != -2) {
stackPrefix.push(operators.charAt(i));
}
}

System.out.println("\n\f Prefix: ");


while(!stackPrefix.isEmpty()) {
System.out.print(stackPrefix.pop());
}
}
}

Capturas de pantalla de ejecución


- Explicación del ejercicio
En este ejercicio se recibe una cadena de texto por teclado, a esa cadena se elimina todos los
espacios en blanco que pueda existir. Luego en un bucle se obtiene cada carácter de la cadena de
texto y se va insertado en una pila.
Luego, se crea dos pilas (prefija, auxiliar) y también una cadena de texto que este conformada por los
operadores aritméticos (+,-,*,/,^). Entonces, ingresamos en un bucle y vamos sacando los elementos
de la pila uno a uno y los analizamos de la siguiente manera. Si es un operando lo insertamos en la
pila prefija, si es un paréntesis derecho “)“se inserta el -2 en la pila auxiliar, si es un paréntesis
izquierdo vamos a insertar en la pila prefija todos los operadores hasta encontrar un paréntesis
derecho (recordar que en la pila auxiliar solo se guarda los índices de los operadores guardados en la
cadena de texto que tiene a todos los operadores). Al encontrar -2 en la pila auxiliar me indica que es
igual a “)“ y como en la prefija no va los paréntesis simplemente lo eliminamos. Si el elemento es un
operador, comparamos con el último elemento de la pila auxiliar y si este tiene mayor prioridad, pues
retiramos de la pila auxiliar y lo insertamos en la pila prefija, hacemos esto hasta que el último
elemento de la pila auxiliar tenga una prioridad menor o igual.
Luego de analizar todos los elementos de la pila salimos del bucle actual, y generamos un bucle que
mientras la pila auxiliar tenga elementos vaya retirándose y añadiéndose en la pila prefija.
Finalmente para poder mostrar solo pasamos a retirar cada elemento de la pila prefija y lo
mostramos en pantalla y ya tenemos nuestra expresión infija.

- Documentación del ejercicio


https://drive.google.com/file/d/1roTYnP9GWfaxffoemnW05XeupDJcZoIH/view?usp=sharing

You might also like