From a41abff9b0958b4429e71623c871807f47965ccd Mon Sep 17 00:00:00 2001 From: Chris Cromer Date: Mon, 20 Jun 2016 13:25:01 -0400 Subject: [PATCH] Initial commit --- .idea/ant.xml | 6 + .idea/artifacts/Estructuras_de_Datos.xml | 47 +++ .idea/codeStyleSettings.xml | 9 + .idea/compiler.xml | 23 ++ .idea/copyright/profiles_settings.xml | 3 + .idea/description.html | 2 + .idea/dictionaries/cromer.xml | 3 + .idea/encodings.xml | 5 + .idea/gradle.xml | 7 + .idea/inspectionProfiles/Project_Default.xml | 21 ++ .../inspectionProfiles/profiles_settings.xml | 7 + .idea/misc.xml | 68 +++++ .idea/modules.xml | 8 + .idea/uiDesigner.xml | 125 ++++++++ .idea/vcs.xml | 6 + Estructuras de Datos.iml | 11 + estructuras_de_datos.properties | 5 + estructuras_de_datos.xml | 248 +++++++++++++++ src/META-INF/MANIFEST.MF | 7 + src/cl/cromer/estructuras/Array.java | 213 +++++++++++++ .../cromer/estructuras/ArrayController.java | 282 +++++++++++++++++ .../cromer/estructuras/BurbujaController.java | 174 +++++++++++ src/cl/cromer/estructuras/Cola.java | 101 ++++++ src/cl/cromer/estructuras/ColaController.java | 236 ++++++++++++++ src/cl/cromer/estructuras/Colores.java | 94 ++++++ src/cl/cromer/estructuras/Grafico.java | 196 ++++++++++++ .../estructuras/InsercionController.java | 174 +++++++++++ src/cl/cromer/estructuras/ListaEnlazada.java | 119 ++++++++ src/cl/cromer/estructuras/Logs.java | 52 ++++ src/cl/cromer/estructuras/Main.java | 66 ++++ src/cl/cromer/estructuras/MenuController.java | 288 ++++++++++++++++++ src/cl/cromer/estructuras/Pila.java | 100 ++++++ src/cl/cromer/estructuras/PilaController.java | 236 ++++++++++++++ .../estructuras/SeleccionController.java | 174 +++++++++++ .../cromer/estructuras/ShellController.java | 174 +++++++++++ .../cromer/estructuras/TextFieldLimited.java | 155 ++++++++++ .../estructuras/bundles/Idioma_en.properties | 86 ++++++ .../estructuras/bundles/Idioma_es.properties | 86 ++++++ .../estructuras/code/arrayOrdenado/buscar | 10 + .../estructuras/code/arrayOrdenado/eliminar | 18 ++ .../estructuras/code/arrayOrdenado/insertar | 13 + .../estructuras/code/arraySimple/buscar | 10 + .../estructuras/code/arraySimple/eliminar | 12 + .../estructuras/code/arraySimple/insertar | 13 + .../cromer/estructuras/code/burbuja/ordenar | 13 + src/cl/cromer/estructuras/code/cola/peek | 4 + src/cl/cromer/estructuras/code/cola/pop | 6 + src/cl/cromer/estructuras/code/cola/push | 6 + .../cromer/estructuras/code/insercion/ordenar | 14 + src/cl/cromer/estructuras/code/pila/peek | 4 + src/cl/cromer/estructuras/code/pila/pop | 6 + src/cl/cromer/estructuras/code/pila/push | 6 + .../cromer/estructuras/code/seleccion/ordenar | 13 + src/cl/cromer/estructuras/css/style.css | 21 ++ src/cl/cromer/estructuras/fxml/array.fxml | 30 ++ src/cl/cromer/estructuras/fxml/burbuja.fxml | 24 ++ src/cl/cromer/estructuras/fxml/cola.fxml | 31 ++ src/cl/cromer/estructuras/fxml/insercion.fxml | 24 ++ src/cl/cromer/estructuras/fxml/main.fxml | 17 ++ src/cl/cromer/estructuras/fxml/menu.fxml | 45 +++ src/cl/cromer/estructuras/fxml/pila.fxml | 30 ++ src/cl/cromer/estructuras/fxml/seleccion.fxml | 24 ++ src/cl/cromer/estructuras/fxml/shell.fxml | 24 ++ src/cl/cromer/estructuras/images/UBBLogo.png | Bin 0 -> 51712 bytes src/cl/cromer/estructuras/images/diagram.png | Bin 0 -> 161775 bytes src/cl/cromer/estructuras/images/diagrama.uml | 170 +++++++++++ 66 files changed, 4205 insertions(+) create mode 100644 .idea/ant.xml create mode 100644 .idea/artifacts/Estructuras_de_Datos.xml create mode 100644 .idea/codeStyleSettings.xml create mode 100644 .idea/compiler.xml create mode 100644 .idea/copyright/profiles_settings.xml create mode 100644 .idea/description.html create mode 100644 .idea/dictionaries/cromer.xml create mode 100644 .idea/encodings.xml create mode 100644 .idea/gradle.xml create mode 100644 .idea/inspectionProfiles/Project_Default.xml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/uiDesigner.xml create mode 100644 .idea/vcs.xml create mode 100644 Estructuras de Datos.iml create mode 100644 estructuras_de_datos.properties create mode 100644 estructuras_de_datos.xml create mode 100644 src/META-INF/MANIFEST.MF create mode 100644 src/cl/cromer/estructuras/Array.java create mode 100644 src/cl/cromer/estructuras/ArrayController.java create mode 100644 src/cl/cromer/estructuras/BurbujaController.java create mode 100644 src/cl/cromer/estructuras/Cola.java create mode 100644 src/cl/cromer/estructuras/ColaController.java create mode 100644 src/cl/cromer/estructuras/Colores.java create mode 100644 src/cl/cromer/estructuras/Grafico.java create mode 100644 src/cl/cromer/estructuras/InsercionController.java create mode 100644 src/cl/cromer/estructuras/ListaEnlazada.java create mode 100644 src/cl/cromer/estructuras/Logs.java create mode 100644 src/cl/cromer/estructuras/Main.java create mode 100644 src/cl/cromer/estructuras/MenuController.java create mode 100644 src/cl/cromer/estructuras/Pila.java create mode 100644 src/cl/cromer/estructuras/PilaController.java create mode 100644 src/cl/cromer/estructuras/SeleccionController.java create mode 100644 src/cl/cromer/estructuras/ShellController.java create mode 100644 src/cl/cromer/estructuras/TextFieldLimited.java create mode 100644 src/cl/cromer/estructuras/bundles/Idioma_en.properties create mode 100644 src/cl/cromer/estructuras/bundles/Idioma_es.properties create mode 100644 src/cl/cromer/estructuras/code/arrayOrdenado/buscar create mode 100644 src/cl/cromer/estructuras/code/arrayOrdenado/eliminar create mode 100644 src/cl/cromer/estructuras/code/arrayOrdenado/insertar create mode 100644 src/cl/cromer/estructuras/code/arraySimple/buscar create mode 100644 src/cl/cromer/estructuras/code/arraySimple/eliminar create mode 100644 src/cl/cromer/estructuras/code/arraySimple/insertar create mode 100644 src/cl/cromer/estructuras/code/burbuja/ordenar create mode 100644 src/cl/cromer/estructuras/code/cola/peek create mode 100644 src/cl/cromer/estructuras/code/cola/pop create mode 100644 src/cl/cromer/estructuras/code/cola/push create mode 100644 src/cl/cromer/estructuras/code/insercion/ordenar create mode 100644 src/cl/cromer/estructuras/code/pila/peek create mode 100644 src/cl/cromer/estructuras/code/pila/pop create mode 100644 src/cl/cromer/estructuras/code/pila/push create mode 100644 src/cl/cromer/estructuras/code/seleccion/ordenar create mode 100644 src/cl/cromer/estructuras/css/style.css create mode 100644 src/cl/cromer/estructuras/fxml/array.fxml create mode 100644 src/cl/cromer/estructuras/fxml/burbuja.fxml create mode 100644 src/cl/cromer/estructuras/fxml/cola.fxml create mode 100644 src/cl/cromer/estructuras/fxml/insercion.fxml create mode 100644 src/cl/cromer/estructuras/fxml/main.fxml create mode 100644 src/cl/cromer/estructuras/fxml/menu.fxml create mode 100644 src/cl/cromer/estructuras/fxml/pila.fxml create mode 100644 src/cl/cromer/estructuras/fxml/seleccion.fxml create mode 100644 src/cl/cromer/estructuras/fxml/shell.fxml create mode 100644 src/cl/cromer/estructuras/images/UBBLogo.png create mode 100644 src/cl/cromer/estructuras/images/diagram.png create mode 100644 src/cl/cromer/estructuras/images/diagrama.uml diff --git a/.idea/ant.xml b/.idea/ant.xml new file mode 100644 index 0000000..d2e8e31 --- /dev/null +++ b/.idea/ant.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/artifacts/Estructuras_de_Datos.xml b/.idea/artifacts/Estructuras_de_Datos.xml new file mode 100644 index 0000000..8f6ef48 --- /dev/null +++ b/.idea/artifacts/Estructuras_de_Datos.xml @@ -0,0 +1,47 @@ + + + $PROJECT_DIR$/out/artifacts/Estructuras_de_Datos + + + file://$PROJECT_DIR$/estructuras_de_datos.xml + all + + + + + file://$PROJECT_DIR$/estructuras_de_datos.xml + clean + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml new file mode 100644 index 0000000..c4c9543 --- /dev/null +++ b/.idea/codeStyleSettings.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..217af47 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,23 @@ + + + + + + diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/description.html b/.idea/description.html new file mode 100644 index 0000000..cc10d56 --- /dev/null +++ b/.idea/description.html @@ -0,0 +1,2 @@ +Simple JavaFX 2.0 application that includes simple .fxml file with attached controller and Main class to quick start. Artifact to build JavaFX application is provided. + \ No newline at end of file diff --git a/.idea/dictionaries/cromer.xml b/.idea/dictionaries/cromer.xml new file mode 100644 index 0000000..3142add --- /dev/null +++ b/.idea/dictionaries/cromer.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..e206d70 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..157a0c1 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..50e443c --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,21 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..3b31283 --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..25f67f9 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..b9e0316 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml new file mode 100644 index 0000000..3b00020 --- /dev/null +++ b/.idea/uiDesigner.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Estructuras de Datos.iml b/Estructuras de Datos.iml new file mode 100644 index 0000000..37cc804 --- /dev/null +++ b/Estructuras de Datos.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/estructuras_de_datos.properties b/estructuras_de_datos.properties new file mode 100644 index 0000000..965674d --- /dev/null +++ b/estructuras_de_datos.properties @@ -0,0 +1,5 @@ +path.variable.kotlin_bundled=/usr/share/intellij-idea-ultimate-edition/plugins/Kotlin/kotlinc +path.variable.maven_repository=/home/cromer/.m2/repository +jdk.home.1.8=/usr/lib/jvm/java-8-jdk +idea.home=/usr/share/intellij-idea-ultimate-edition +javac2.instrumentation.includeJavaRuntime=false \ No newline at end of file diff --git a/estructuras_de_datos.xml b/estructuras_de_datos.xml new file mode 100644 index 0000000..a07107b --- /dev/null +++ b/estructuras_de_datos.xml @@ -0,0 +1,248 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/META-INF/MANIFEST.MF b/src/META-INF/MANIFEST.MF new file mode 100644 index 0000000..2559fe9 --- /dev/null +++ b/src/META-INF/MANIFEST.MF @@ -0,0 +1,7 @@ +Manifest-Version: 1.0 +Permissions: sandbox +JavaFX-Version: 8.0 +Class-Path: /cl/cromer/estructuras +Created-By: Chris Cromer +Main-Class: cl.cromer.estructuras.Main + diff --git a/src/cl/cromer/estructuras/Array.java b/src/cl/cromer/estructuras/Array.java new file mode 100644 index 0000000..569cf03 --- /dev/null +++ b/src/cl/cromer/estructuras/Array.java @@ -0,0 +1,213 @@ +package cl.cromer.estructuras; + +/** + * Crear una estructura de dato de tipo array. + * @author Chris Cromer + */ +public class Array { + /** + * El array. + */ + private String array[]; + + /** + * La cantidad de elementos en el array. + */ + private int size; + + /** + * Si es de tipo ordenado o simple. + */ + private boolean ordered; + + /** + * Crear el array con el tamaño pasador por argumento. + * @param temano int: El temaño del array a crear. + */ + public Array(int temano) { + this.array = new String[temano]; + size = 0; + ordered = false; + } + + /** + * Devolver la cantidad de elementos en el array. + * @return int: Devolver la cantidad de elementos en el array. + */ + public int size() { + return size; + } + + /** + * Dovolver si el tipo es ordenado o no. + * @return boolean: Si el tipo de array es ordenado. + */ + public boolean isOrdered() { + return ordered; + } + + /** + * Cambiar el tipo de array entre ordenado o simple. + * @param ordered boolean: Si es verdad, es de tipo ordenado, sino el tipo es simple. + */ + public void setOrdered(boolean ordered) { + this.ordered = ordered; + } + + /** + * Insertar un valor al array. + * @param valor int: El valor a insertar. + * @return boolean: Verdad si fue exitoso, sino falso. + */ + public boolean insertar(int valor) { + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + array[i] = String.valueOf(valor); + size++; + return true; + } + else if (array[i].equals(String.valueOf(valor))) { + // Ya existe el valor en el array + return false; + } + } + return false; + } + + /** + * Eliminar un valor del array si existe. + * @param valor int: El valor a eliminar. + * @return boolean: Verdad si fue encontrado y borrado, sino falso. + */ + public boolean eliminar(int valor) { + boolean borrado = false; + for (int i = 0; i < array.length; i++) { + if (array[i] != null && array[i].equals(String.valueOf(valor))) { + // Eliminar el valor + array[i] = null; + borrado=true; + size--; + if (ordered) { + for (int j = i; j < array.length; j++) { + if (j != array.length - 1) { + // Correr la array hacia arriba + array[j] = array[j + 1]; + } + } + array[array.length-1] = null; + } + else { + break; + } + } + } + return borrado; + } + + /** + * Buscar si existe un valor dentro el array. + * @param valor int: Valor a buscar. + * @return int: Devuelve el indice donde fue encontrado, o -1 si no fue encontrado. + */ + public int buscar(int valor) { + for (int i = 0; i < array.length; i++) { + if (array[i] != null && array[i].equals(String.valueOf(valor))) { + // Se encontró + return i; + } + } + // No se encontró + return -1; + } + + /** + * Devolver el valor que está guardado en cada indice del array. Se usa para construir la grafica. + * @param indice int: El indice que desea ver. + * @return String: El valor que está en dicho indice. + */ + public String getIndice(int indice) { + if (indice >= 0 && indice < array.length) { + return array[indice]; + } + else { + return null; + } + } + + /** + * Ordenar el array usando burbuja. + * @param paso boolean: Si es verdad, solo hago en paso del ordenamiento, sino ordenear todos los elementos. + * @return boolean: Verdad si algo cambió, sino falso. + */ + public boolean burbuja(boolean paso) { + boolean cambio = false; + + for (int i = size() - 1; i > 1; i--) { + for (int j = 0; j < i; j++) { + if (Integer.valueOf(array[j]) > Integer.valueOf(array[j+1])) { + String temp = array[j]; + array[j] = array[j+1]; + array[j+1] = temp; + cambio = true; + if (paso) { + return true; + } + } + } + } + + return cambio; + } + + /** + * Ordenar el array usando inserción. + * @param paso boolean: Si es verdad, solo hago en paso del ordenamiento, sino ordenear todos los elementos. + * @return boolean: Verdad si algo cambió, sino falso. + */ + public boolean insercion(boolean paso) { + boolean cambio = false; + + for (int i = 1; i < size(); i++) { + String temp = array[i]; + int j = i; + while (j > 0 && Integer.valueOf(array[j-1]) >= Integer.valueOf(temp)) { + array[j] = array[j-1]; + --j; + cambio = true; + } + array[j] = temp; + if (paso && cambio) { + return true; + } + } + + return cambio; + } + + /** + * Ordenar el array usando selección. + * @param paso boolean: Si es verdad, solo hago en paso del ordenamiento, sino ordenear todos los elementos. + * @return boolean: Verdad si algo cambió, sino falso. + */ + public boolean seleccion(boolean paso) { + boolean cambio = false; + + for (int i = 0; i < size() - 1; i++) { + int minimo = i; + for (int j = i + 1; j < size(); j++) { + if (Integer.valueOf(array[j]) < Integer.valueOf(array[minimo])) { + minimo = j; + cambio = true; + } + } + String temp = array[i]; + array[i] = array[minimo]; + array[minimo] = temp; + if (paso && cambio) { + return true; + } + } + + return cambio; + } +} diff --git a/src/cl/cromer/estructuras/ArrayController.java b/src/cl/cromer/estructuras/ArrayController.java new file mode 100644 index 0000000..29a7d89 --- /dev/null +++ b/src/cl/cromer/estructuras/ArrayController.java @@ -0,0 +1,282 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.VBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; +import java.util.logging.Level; + +/** + * Esta clase es para controlar todos la interfaz de Array. + * @author Chris Cromer + */ +public class ArrayController implements Initializable { + + /** + * La caja para ingresar textos. + */ + @FXML private TextFieldLimited valorArray; + + /** + * Donde poner el contenido de array. + */ + @FXML private VBox contenidoArray; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoArray; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * El array usado en la aplicación. + */ + private Array array; + + /** + * Grafico rectangulos. + */ + private Grafico grafico; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + scene = null; + Colores colores = new Colores(); + + for (int i = 0; i < 10; i++) { + contenidoArray.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i))); + colores.siguinteColor(); + } + } + + /** + * Llenar el array con numeros al azar. + */ + @FXML + protected void botonLlenar() { + if (scene == null) { + initializeArray(); + } + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = array.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + } + generarGrafico(); + } + + /** + * Vaciar el array de todos los valores. + */ + @FXML + protected void botonVaciar() { + if (scene == null) { + initializeArray(); + } + + if (array.isOrdered()) { + array = new Array(10); + array.setOrdered(true); + } + else { + array = new Array(10); + array.setOrdered(false); + } + generarGrafico(); + } + + /** + * Insertar un valor al array y mostrar el codigo en la pantalla. + */ + @FXML + protected void botonInsertar() { + if (scene == null) { + initializeArray(); + } + + // Mostrar el codigo + String tipo = (array.isOrdered())?"Ordenado":"Simple"; + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/array" + tipo + "/insertar")).useDelimiter("\\Z").next(); + codigoArray.setText(codigoTexto); + + if (valorArray.getText() != null && !valorArray.getText().trim().equals("")) { + try { + boolean exito = array.insertar(Integer.valueOf(valorArray.getText())); + if (exito) { + generarGrafico(); + } + else { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + if (array.size() == 10) { + dialog.setContentText(resourceBundle.getString("arrayLleno")); + } + else { + dialog.setContentText(resourceBundle.getString("arrayValorExiste")); + } + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + } + catch (NumberFormatException exception) { + // El error no es fatal, sigue + Logs.log(Level.WARNING, "No es tipo int."); + errorNoValor(); + } + } + else { + errorNoValor(); + } + } + + /** + * Eliminar un valor del array si existe y mostrar el codigo en la pantalla. + */ + @FXML + protected void botonEliminar() { + if (scene == null) { + initializeArray(); + } + + // Mostrar el codigo + String tipo = (array.isOrdered())?"Ordenado":"Simple"; + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/array" + tipo + "/eliminar")).useDelimiter("\\Z").next(); + codigoArray.setText(codigoTexto); + + try { + if (valorArray.getText() != null && !valorArray.getText().trim().equals("")) { + boolean exito = array.eliminar(Integer.valueOf(valorArray.getText())); + if (exito) { + generarGrafico(); + } + else { + errorNoEsta(); + } + } + else { + errorNoValor(); + } + } + catch (NumberFormatException exception) { + // El error no es fatal, sigue + Logs.log(Level.WARNING, "No es tipo int."); + errorNoValor(); + } + } + + /** + * Buscar si existe un elemento en el array y mostrar el codigo en la pantalla + * Si existe el valor destacarlo. + */ + @FXML + protected void botonBuscar() { + if (scene == null) { + initializeArray(); + } + + // Mostrar el codigo + String tipo = (array.isOrdered())?"Ordenado":"Simple"; + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/array" + tipo + "/buscar")).useDelimiter("\\Z").next(); + codigoArray.setText(codigoTexto); + + try { + if (valorArray.getText() != null && !valorArray.getText().trim().equals("")) { + int encontrado = array.buscar(Integer.valueOf(valorArray.getText())); + if (encontrado != -1) { + generarGrafico(); + grafico = new Grafico(scene); + grafico.destacer(encontrado, "rectangulo"); + } + else { + errorNoEsta(); + } + } + else { + errorNoValor(); + } + } + catch (NumberFormatException exception) { + // El error no es fatal, sigue + Logs.log(Level.WARNING, "No es tipo int."); + errorNoValor(); + } + } + + /** + * Se muestra un error si la persona no ingresa un valor en el TextField. + */ + private void errorNoValor() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("arrayNoValor")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Error cuando el valor no está en el array. + */ + private void errorNoEsta() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("arrayNoEsta")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Crear el array de temaño 10. La scene está usado para saber si es de tipo ordenado o simple segun el ménu. + */ + private void initializeArray() { + scene = contenidoArray.getScene(); + grafico = new Grafico(scene); + this.array = new Array(10); + Array array = (Array) scene.getUserData(); + this.array.setOrdered(array.isOrdered()); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + grafico.removerDestacar(); + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(array.getIndice(i)); + } + } +} diff --git a/src/cl/cromer/estructuras/BurbujaController.java b/src/cl/cromer/estructuras/BurbujaController.java new file mode 100644 index 0000000..13b79e5 --- /dev/null +++ b/src/cl/cromer/estructuras/BurbujaController.java @@ -0,0 +1,174 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.layout.HBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; + +/** + * Esta clase es para controlar todos la interfaz de Burbuja. + * @author Chris Cromer + */ +public class BurbujaController implements Initializable { + /** + * Donde poner el contenido de array. + */ + @FXML private HBox contenidoBurbuja; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoBurbuja; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * El array usado en la aplicación. + */ + private Array array; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + scene = null; + + Colores colores = new Colores(); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + array = new Array(10); + array.setOrdered(true); + + for (int i = 0; i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + contenidoBurbuja.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i), String.valueOf(numero))); + colores.siguinteColor(); + } + } + + /** + * Crear un array nuevo. + */ + @FXML + protected void botonNuevo() { + if (scene == null) { + initializeScene(); + } + + array = new Array(10); + array.setOrdered(true); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = array.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + } + generarGrafico(); + } + + /** + * Ordenarlo paso por paso. + */ + @FXML + protected void botonPaso() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/burbuja/ordenar")).useDelimiter("\\Z").next(); + codigoBurbuja.setText(codigoTexto); + + if (!array.burbuja(true)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Ordenarlo completamente. + */ + @FXML + protected void botonCorrer() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/burbuja/ordenar")).useDelimiter("\\Z").next(); + codigoBurbuja.setText(codigoTexto); + + if (!array.burbuja(false)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Se muestra un error si el array ya está ordenado. + */ + private void errorYaOrdenado() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("burbujaYaOrdenado")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Crear el array de temaño 10. + */ + private void initializeScene() { + scene = contenidoBurbuja.getScene(); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(array.getIndice(i)); + } + } +} diff --git a/src/cl/cromer/estructuras/Cola.java b/src/cl/cromer/estructuras/Cola.java new file mode 100644 index 0000000..079e9fd --- /dev/null +++ b/src/cl/cromer/estructuras/Cola.java @@ -0,0 +1,101 @@ +package cl.cromer.estructuras; + +/** + * Crear una estructura de dato de tipo cola. + * @author Chris Cromer + */ +public class Cola { + /** + * La cola. + */ + private String cola[]; + + /** + * La cantidad de elementos que están en la cola. + */ + private int size; + + /** + * Inicializar. + */ + public Cola() { + this.cola = null; + size = 0; + } + + /** + * Devolver la cantidad de elementos que están en la cola. + * @return int: La cantidad de elementos. + */ + public int size() { + return size; + } + + /** + * Push un valor en la cola encima. + * @param valor int: El valor a push. + */ + public void push(int valor) { + if (this.cola != null) { + String cola[] = new String[this.cola.length + 1]; + int i; + for (i = 0; i < this.cola.length; i++) { + cola[i] = this.cola[i]; + } + cola[i] = String.valueOf(valor); + this.cola = cola; + size++; + } + else { + String pila[] = new String[1]; + pila[0] = String.valueOf(valor); + this.cola = pila; + size++; + } + } + + /** + * Pop un valor del principio de la cola. + * @return boolean: Verdad si fue exitoso. + */ + public boolean pop() { + if (this.cola != null) { + String cola[] = new String[this.cola.length -1]; + // Nueva array sin el valor del primer + System.arraycopy(this.cola, 1, cola, 0, cola.length); + this.cola = cola; + size--; + return true; + } + else { + return false; + } + } + + /** + * Peek al valor que está al principio de la cola. + * @return int: El valor que está al principio de la cola. + */ + public int peek() { + if (this.cola != null && size() > 0) { + return Integer.valueOf(cola[0]); + } + else { + return Integer.MIN_VALUE; + } + } + + /** + * Devolver el valor que está en un indice de la cola. + * @param indice int: El indice que desea devolver. + * @return String: El valor que está guardado en el indice. + */ + public String getIndice(int indice) { + if (indice >= 0 && indice < cola.length) { + return cola[indice]; + } + else { + return null; + } + } +} diff --git a/src/cl/cromer/estructuras/ColaController.java b/src/cl/cromer/estructuras/ColaController.java new file mode 100644 index 0000000..e448918 --- /dev/null +++ b/src/cl/cromer/estructuras/ColaController.java @@ -0,0 +1,236 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.layout.VBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; +import java.util.logging.Level; + +/** + * Esta clase es para controlar todos la interfaz de Cola. + * @author Chris Cromer + */ +public class ColaController implements Initializable { + /** + * La caja para ingresar textos. + */ + @FXML private TextFieldLimited valorCola; + + /** + * Donde poner el contenido de array. + */ + @FXML private VBox contenidoCola; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoCola; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * La cola usado en la aplicación. + */ + private Cola cola; + + /** + * Grafico rectangulos. + */ + private Grafico grafico; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + cola = new Cola(); + + scene = null; + Colores colores = new Colores(); + + for (int i = 9; i >= 0; i--) { + contenidoCola.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i))); + colores.siguinteColor(); + } + } + + /** + * Llenar la cola con numeros al azar. + */ + @FXML + protected void botonLlenar() { + if (scene == null) { + scene = contenidoCola.getScene(); + grafico = new Grafico(scene); + } + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = cola.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + cola.push(numero); + } + generarGrafico(); + } + + /** + * Vaciar la cola de todos los valores. + */ + @FXML + protected void botonVaciar() { + if (scene == null) { + scene = contenidoCola.getScene(); + grafico = new Grafico(scene); + } + + cola = new Cola(); + generarGrafico(); + } + + /** + * Push un valor a la cola y mostrar el codigo en la pantalla. + */ + @FXML + protected void botonPush() { + if (scene == null) { + scene = contenidoCola.getScene(); + grafico = new Grafico(scene); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/cola/push")).useDelimiter("\\Z").next(); + codigoCola.setText(codigoTexto); + + if (valorCola.getText() != null && !valorCola.getText().trim().equals("")) { + try { + if (cola.size() < 10) { + cola.push(Integer.valueOf(valorCola.getText())); + generarGrafico(); + } + else { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("colaLlena")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + } + catch (NumberFormatException exception) { + // El error no es fatal, sigue + Logs.log(Level.WARNING, "No es tipo int."); + errorNoValor(); + } + } + else { + errorNoValor(); + } + } + + /** + * Pop un valor de la pila si existe y mostrar el codigo en la pantalla. + */ + @FXML + protected void botonPop() { + if (scene == null) { + scene = contenidoCola.getScene(); + grafico = new Grafico(scene); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/cola/pop")).useDelimiter("\\Z").next(); + codigoCola.setText(codigoTexto); + + if (cola.size() > 0) { + cola.pop(); + generarGrafico(); + } + else { + errorVacia(); + } + } + + /** + * Peek a ver si existe un elemento en la pila y mostrar el codigo en la pantalla + * Si existe un valor destacarlo. + */ + @FXML + protected void botonPeek() { + if (scene == null) { + scene = contenidoCola.getScene(); + grafico = new Grafico(scene); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/cola/peek")).useDelimiter("\\Z").next(); + codigoCola.setText(codigoTexto); + + int encontrado = cola.peek(); + if (encontrado != Integer.MIN_VALUE) { + generarGrafico(); + grafico.destacer(0, "rectangulo"); + } + else { + errorVacia(); + } + } + + /** + * Se muestra un error si la persona no ingresa un valor en el TextField. + */ + private void errorNoValor() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("colaNoValor")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Error cuando la pila está vacía. + */ + private void errorVacia() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("colaVacia")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + grafico.removerDestacar(); + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(cola.getIndice(i)); + } + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/Colores.java b/src/cl/cromer/estructuras/Colores.java new file mode 100644 index 0000000..a04b813 --- /dev/null +++ b/src/cl/cromer/estructuras/Colores.java @@ -0,0 +1,94 @@ +package cl.cromer.estructuras; + +import javafx.scene.paint.Color; + +/** + * Rotación de colores. + * @author Chris Cromer + */ +public class Colores { + /** + * Cuantos colores estan definidos en esta clase. + */ + static public int MAX_COLORS = 7; + + /** + * El color actual en forma numerica. + */ + private int color; + + /** + * El color de texto actual. + */ + private Color texto; + + /** + * El color de fondo actual. + */ + private Color fondo; + + /** + * Inicializar el primer color. + */ + public Colores() { + siguinteColor(); + } + + /** + * Cambiar el color al siguinte. Si no hay, voler al primer. + */ + public void siguinteColor() { + switch (color) { + case 1: + color = 2; + texto = Color.WHITE; + fondo = Color.RED; + break; + case 2: + color = 3; + texto = Color.BLACK; + fondo = Color.WHITE; + break; + case 3: + color = 4; + texto = Color.BLACK; + fondo = Color.PINK; + break; + case 4: + color = 5; + texto = Color.BLACK; + fondo = Color.YELLOW; + break; + case 5: + color = 6; + texto = Color.BLACK; + fondo = Color.GREEN; + break; + case 6 : + color = 7; + texto = Color.BLACK; + fondo = Color.ORANGE; + break; + default: + color = 1; + texto = Color.WHITE; + fondo = Color.BLUE; + } + } + + /** + * Devolver el color del texto actual. + * @return Color: Color del texto. + */ + public Color getTexto() { + return texto; + } + + /** + * Devolver el color del fondo actual. + * @return Color: Color del fondo. + */ + public Color getFondo() { + return fondo; + } +} diff --git a/src/cl/cromer/estructuras/Grafico.java b/src/cl/cromer/estructuras/Grafico.java new file mode 100644 index 0000000..4efa787 --- /dev/null +++ b/src/cl/cromer/estructuras/Grafico.java @@ -0,0 +1,196 @@ +package cl.cromer.estructuras; + +import javafx.animation.Animation; +import javafx.animation.PauseTransition; +import javafx.animation.SequentialTransition; +import javafx.scene.Scene; +import javafx.scene.layout.StackPane; +import javafx.scene.paint.Color; +import javafx.scene.shape.Circle; +import javafx.scene.shape.Rectangle; +import javafx.scene.text.Text; +import javafx.util.Duration; + +/** + * Esta clase es para trabajar con graficos. + * @author Chris Cromer + */ +public class Grafico { + /** + * Contiene la animación de destacar. + */ + private SequentialTransition blinkTransition; + + /** + * El valor de cual caja está destacado actualmente + */ + private int destacado; + + /** + * El tipo de objeto que está destacado. + */ + private String tipo; + + /** + * El color original de fondo para volver cuando no es destacado. + */ + private Color destacadoBG; + + /** + * El color original de text para volver cuando no es destacado. + */ + private Color destacadoFG; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Graficar una escena. + * @param scene La scene a destacar. + */ + public Grafico(Scene scene) { + this.scene = scene; + destacado = -1; + } + + /** + * Crear un rectangulo con texto adentro. + * @param colores Colores: Los colores para dar color al rectangulo. + * @param label String: El texto por el ID de fxml. + * @return StackPane: Devolver el stackpane que contiene el rectangulo y texto. + */ + public static StackPane crearCaja(Colores colores, String label) { + Rectangle rectangle = new Rectangle(); + rectangle.setHeight(40); + rectangle.setWidth(40); + rectangle.setFill(colores.getFondo()); + rectangle.setStroke(Color.BLACK); + rectangle.setId("border_" + label); + Text text = new Text(); + text.setId("caja_" + label); + text.setStroke(colores.getTexto()); + + StackPane stackPane = new StackPane(); + stackPane.getChildren().addAll(rectangle, text); + return stackPane; + } + + /** + * Crear un rectangulo con texto adentro. + * @param colores Colores: Los colores para dar color al rectangulo. + * @param label String: El texto por el ID de fxml. + * @param texto String: El texto a colocar dentro el rectangulo. + * @return StackPane: Devolver el stackpane que contiene el rectangulo y texto. + */ + public static StackPane crearCaja(Colores colores, String label, String texto) { + Rectangle rectangle = new Rectangle(); + rectangle.setHeight(40); + rectangle.setWidth(40); + rectangle.setFill(colores.getFondo()); + rectangle.setStroke(Color.BLACK); + rectangle.setId("border_" + label); + Text text = new Text(); + text.setId("caja_" + label); + text.setStroke(colores.getTexto()); + text.setText(texto); + + StackPane stackPane = new StackPane(); + stackPane.getChildren().addAll(rectangle, text); + return stackPane; + } + + /** + * Destacar un elemento + * @param valor int: El indice a destacar. + * @param tipo String: El tipo de objeto a destacer(rectangulo o cicurlo) + */ + public void destacer(int valor, String tipo) { + if (!tipo.equals("rectangulo") && !tipo.equals("circulo")) { + return; + } + this.tipo = tipo; + destacado = valor; + Colores colores = new Colores(); + Rectangle rectangle = null; + Circle circle = null; + if (tipo.equals("rectangulo")) { + rectangle = (Rectangle) scene.lookup("#border_" + String.valueOf(valor)); + destacadoBG = (Color) rectangle.getFill(); + } + else if (tipo.equals("circulo")) { + circle = (Circle) scene.lookup("#border_" + String.valueOf(valor)); + destacadoBG = (Color) circle.getFill(); + } + Text text = (Text) scene.lookup("#caja_" + String.valueOf(valor)); + destacadoFG = (Color) text.getStroke(); + PauseTransition changeColor[] = new PauseTransition[Colores.MAX_COLORS]; + for (int i = 0; i < Colores.MAX_COLORS; i++) { + if (tipo.equals("rectangulo")) { + changeColor[i] = createPauseTransition(rectangle, text, colores.getFondo(), colores.getTexto()); + } + else if (tipo.equals("circulo")) { + changeColor[i] = createPauseTransition(circle, text, colores.getFondo(), colores.getTexto()); + } + colores.siguinteColor(); + } + blinkTransition = new SequentialTransition(changeColor); + blinkTransition.setCycleCount(Animation.INDEFINITE); + blinkTransition.play(); + } + + /** + * Remover el efecto de destacar. + */ + public void removerDestacar() { + if (destacado != -1) { + blinkTransition.stop(); + if (tipo.equals("rectangulo")) { + Rectangle rectangle = (Rectangle) scene.lookup("#border_" + String.valueOf(destacado)); + rectangle.setFill(destacadoBG); + } + else if (tipo.equals("circulo")) { + Circle circle = (Circle) scene.lookup("#border_" + String.valueOf(destacado)); + circle.setFill(destacadoBG); + } + Text text = (Text) scene.lookup("#caja_" + String.valueOf(destacado)); + text.setStroke(destacadoFG); + destacado = -1; + } + } + + /** + * Crear un animacion de transicion usando colores que cambian. + * @param rectangle Rectangle: El objeto que desea animar. + * @param text Text: El texto que desea animar. + * @param colorBackground Color: Color del fondo de destacer. + * @param colorText Color: Color del texto. + * @return PauseTransition: La transition creado con los elementos y colores. + */ + private static PauseTransition createPauseTransition(Rectangle rectangle , Text text, Color colorBackground, Color colorText) { + PauseTransition changeColor = new PauseTransition(new Duration(100)); + changeColor.setOnFinished(actionEvent -> { + rectangle.setFill(colorBackground); + text.setStroke(colorText); + }); + return changeColor ; + } + + /** + * Crear un animacion de transicion usando colores que cambian. + * @param circle Circle: El objeto que desea animar. + * @param text Text: El texto que desea animar. + * @param colorBackground Color: Color del fondo de destacer. + * @param colorText Color: Color del texto. + * @return PauseTransition: La transition creado con los elementos y colores. + */ + private static PauseTransition createPauseTransition(Circle circle , Text text, Color colorBackground, Color colorText) { + PauseTransition changeColor = new PauseTransition(new Duration(100)); + changeColor.setOnFinished(actionEvent -> { + circle.setFill(colorBackground); + text.setStroke(colorText); + }); + return changeColor ; + } +} diff --git a/src/cl/cromer/estructuras/InsercionController.java b/src/cl/cromer/estructuras/InsercionController.java new file mode 100644 index 0000000..076b9d8 --- /dev/null +++ b/src/cl/cromer/estructuras/InsercionController.java @@ -0,0 +1,174 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.layout.HBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; + +/** + * Esta clase es para controlar todos la interfaz de Inserción. + * @author Chris Cromer + */ +public class InsercionController implements Initializable { + /** + * Donde poner el contenido de array. + */ + @FXML private HBox contenidoInsercion; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoInsercion; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * El array usado en la aplicación. + */ + private Array array; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + scene = null; + + Colores colores = new Colores(); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + array = new Array(10); + array.setOrdered(true); + + for (int i = 0; i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + contenidoInsercion.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i), String.valueOf(numero))); + colores.siguinteColor(); + } + } + + /** + * Crear un array nuevo. + */ + @FXML + protected void botonNuevo() { + if (scene == null) { + initializeScene(); + } + + array = new Array(10); + array.setOrdered(true); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = array.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + } + generarGrafico(); + } + + /** + * Ordenarlo paso por paso. + */ + @FXML + protected void botonPaso() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/insercion/ordenar")).useDelimiter("\\Z").next(); + codigoInsercion.setText(codigoTexto); + + if (!array.insercion(true)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Ordenarlo completamente. + */ + @FXML + protected void botonCorrer() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/insercion/ordenar")).useDelimiter("\\Z").next(); + codigoInsercion.setText(codigoTexto); + + if (!array.insercion(false)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Se muestra un error si el array ya está ordenado. + */ + private void errorYaOrdenado() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("insercionYaOrdenado")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Crear el array de temaño 10. + */ + private void initializeScene() { + scene = contenidoInsercion.getScene(); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(array.getIndice(i)); + } + } +} diff --git a/src/cl/cromer/estructuras/ListaEnlazada.java b/src/cl/cromer/estructuras/ListaEnlazada.java new file mode 100644 index 0000000..db6577e --- /dev/null +++ b/src/cl/cromer/estructuras/ListaEnlazada.java @@ -0,0 +1,119 @@ +package cl.cromer.estructuras; + +public class ListaEnlazada { + private Enlace lista; + + public ListaEnlazada() { + lista = null; + } + + public Enlace buscar(int llave) { + if (this.lista != null) { + // La lista no es vacia + Enlace lista = this.lista; + while (lista.getLlave() != llave) { + // Buscar hasta la llave es encontraddo + if (lista.getSiguente() != null) { + // Buscar en la sigenute enlace + lista = lista.getSiguente(); + } + else { + // No se encuentra + return null; + } + } + // Se encontró + return lista; + } + else { + // La lista es vacia, nada para buscar + return null; + } + } + + public boolean insertar(int llave, int valor) { + if (buscar(llave) == null) { + // Crear una enlace y agregarla a la lista + Enlace nueva = new Enlace(); + nueva.setLlave(llave); + nueva.setValor(valor); + nueva.setSiguente(lista); + lista = nueva; + return true; + } + else { + // Se falló porque la llave ya existe + return false; + } + } + + public boolean eliminar(int llave) { + if (lista != null) { + // La lista no es vacia + Enlace lista = this.lista; + Enlace previo = lista; + while (lista.getLlave() != llave) { + // Buscar hasta la llave es encontraddo + if (lista.getSiguente() != null) { + // Buscar en la sigenute enlace + previo = lista; + lista = lista.getSiguente(); + } + else { + // No se encuentra + return false; + } + } + // Se encontró + if (lista == this.lista) { + // Si es la primera enlace, cambiarla al siguente enlace + this.lista = this.lista.getSiguente(); + } + else { + // Sino cortar esta enlace de la lista + previo.setSiguente(lista.getSiguente()); + } + return true; + } + else { + // La lista es vacia, no hay nada para eliminar + return false; + } + } + + // Estructura de enlaces + public class Enlace { + private int llave; + private int valor; + private Enlace siguente; + + protected Enlace() { + siguente = null; + } + + protected int getLlave() { + return llave; + } + + protected void setLlave(int llave) { + this.llave = llave; + } + + protected int getValor() { + return valor; + } + + protected void setValor(int valor) { + this.valor = valor; + } + + protected Enlace getSiguente() { + return siguente; + } + + protected void setSiguente(Enlace siguente) { + this.siguente = siguente; + } + } +} + diff --git a/src/cl/cromer/estructuras/Logs.java b/src/cl/cromer/estructuras/Logs.java new file mode 100644 index 0000000..1b74234 --- /dev/null +++ b/src/cl/cromer/estructuras/Logs.java @@ -0,0 +1,52 @@ +package cl.cromer.estructuras; + +import java.io.IOException; +import java.util.logging.FileHandler; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.logging.SimpleFormatter; + +/** + * Esta clase es para configurar el logeo de la aplicación. + * @author Chris Cromer + */ +public class Logs { + /** + * Nombre de archivo para guardar los logs. + */ + static final public String LOGFILE = "./EDD.log"; + + /** + * Nombre del log. + */ + static final public String LOGNAME = "EDD"; + + /** + * Crear un logger usando {@value #LOGNAME}. Guardar los logs en el archivo de {@value #LOGFILE}. Pero solo logear si Main.DEBUG es vardad. + */ + public Logs() { + if (Main.DEBUG) { + Logger logger = Logger.getLogger(LOGNAME); + try { + FileHandler fileHandler = new FileHandler(LOGFILE, true); + logger.addHandler(fileHandler); + SimpleFormatter formatter = new SimpleFormatter(); + fileHandler.setFormatter(formatter); + } + catch (SecurityException | IOException e) { + e.printStackTrace(); + } + } + } + + /** + * Agregar un log al logger. + * @param level Level: El tipo de error o mensaje que ha sido generado. + * @param mensaje String: El mensaje de lo que pasó. + */ + static public void log(Level level, String mensaje) { + if (Main.DEBUG) { + Logger.getLogger(LOGNAME).log(level, mensaje); + } + } +} diff --git a/src/cl/cromer/estructuras/Main.java b/src/cl/cromer/estructuras/Main.java new file mode 100644 index 0000000..89de62d --- /dev/null +++ b/src/cl/cromer/estructuras/Main.java @@ -0,0 +1,66 @@ +package cl.cromer.estructuras; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; + +import java.io.IOException; +import java.util.Locale; +import java.util.ResourceBundle; +import java.util.logging.Level; + +/** + * Estructuras de Datos + * Creado como proyecto semestral para la asignatura de estructuras de datos por la profesora Karina Rojas y el profesor Jorge Elgueta. + * Creado en 2016-1 + * @author Chris Cromer + * @version 1.0 + */ +public class Main extends Application { + /** + * Estado de depuración. + */ + static final public boolean DEBUG = false; + + /** + * Crear el stage y la scene para la aplicación grafica. + * @param stage El primer stage donde va todas las cosas visuales. + */ + @Override + public void start(Stage stage) { + Locale locale = new Locale("es", "ES"); + ResourceBundle resourceBundle = ResourceBundle.getBundle("cl.cromer.estructuras.bundles.Idioma", locale); + + try { + Parent parent = FXMLLoader.load(getClass().getResource("/cl/cromer/estructuras/fxml/main.fxml"), ResourceBundle.getBundle("cl.cromer.estructuras.bundles.Idioma", locale)); + stage.setTitle(resourceBundle.getString("titulo")); + Scene scene = new Scene(parent, 1024, 768); + scene.getStylesheets().add("/cl/cromer/estructuras/css/style.css"); + stage.setScene(scene); + } + catch (IOException exception) { + // Este error es fatal, hay que cerrar la aplicación. + Logs.log(Level.SEVERE, "No se pudo abrir el archivo de fxml."); + stage.close(); + } + + //stage.setMaximized(true); + stage.setMinHeight(640); + stage.setMinWidth(768); + stage.show(); + } + + /** + * Inicilizar el logeo y lanzar la interfaz grafica. + * @param args String[]: Argumentos desde la consola. + */ + public static void main(String[] args) { + if (DEBUG) { + new Logs(); + } + + launch(args); + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/MenuController.java b/src/cl/cromer/estructuras/MenuController.java new file mode 100644 index 0000000..23d8763 --- /dev/null +++ b/src/cl/cromer/estructuras/MenuController.java @@ -0,0 +1,288 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.fxml.Initializable; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; + +import java.io.IOException; +import java.net.URL; +import java.util.Locale; +import java.util.Optional; +import java.util.ResourceBundle; +import java.util.logging.Level; + +/** + * Controlar las acciones cuando una opción es elegido en el menu. + */ +public class MenuController extends VBox implements Initializable { + /** + * La barra del menu. + */ + @FXML private MenuBar menuBar; + + /** + * Los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * Inicialicar el menu con el idioma. + * @param location URL: Tiene URL de FXML en uso. + * @param resourceBundle: Tiene los idiomas. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + } + + /** + * Click en Array Simple. + */ + @FXML + protected void menuArraySimple() { + Array array = new Array(1); + array.setOrdered(false); + loadStage( + resourceBundle.getString("tituloArraySimple"), + "/cl/cromer/estructuras/fxml/array.fxml", + "/cl/cromer/estructuras/css/style.css", + array + ); + } + + /** + * Click en Array Ordenado. + */ + @FXML + protected void menuArrayOrdenado() { + Array array = new Array(1); + array.setOrdered(true); + loadStage( + resourceBundle.getString("tituloArrayOrdenado"), + "/cl/cromer/estructuras/fxml/array.fxml", + "/cl/cromer/estructuras/css/style.css", + array + ); + } + + /** + * Click en Burbuja. + */ + @FXML + protected void menuBurbuja() { + loadStage( + resourceBundle.getString("tituloBurbuja"), + "/cl/cromer/estructuras/fxml/burbuja.fxml", + "/cl/cromer/estructuras/css/style.css" + ); + } + + /** + * Click en Inserción. + */ + @FXML + protected void menuInsercion() { + loadStage( + resourceBundle.getString("tituloInsercion"), + "/cl/cromer/estructuras/fxml/insercion.fxml", + "/cl/cromer/estructuras/css/style.css" + ); + } + + /** + * Click en Selecion. + */ + @FXML + protected void menuSeleccion() { + loadStage( + resourceBundle.getString("tituloSeleccion"), + "/cl/cromer/estructuras/fxml/seleccion.fxml", + "/cl/cromer/estructuras/css/style.css" + ); + } + + /** + * Click en Selecion. + */ + @FXML + protected void menuShell() { + loadStage( + resourceBundle.getString("tituloShell"), + "/cl/cromer/estructuras/fxml/shell.fxml", + "/cl/cromer/estructuras/css/style.css" + ); + } + + /** + * Click en Pila. + */ + @FXML + protected void menuPila() { + loadStage( + resourceBundle.getString("tituloPila"), + "/cl/cromer/estructuras/fxml/pila.fxml", + "/cl/cromer/estructuras/css/style.css" + ); + } + + /** + * Click en Cola. + */ + @FXML + protected void menuCola() { + loadStage( + resourceBundle.getString("tituloCola"), + "/cl/cromer/estructuras/fxml/cola.fxml", + "/cl/cromer/estructuras/css/style.css" + ); + } + + /** + * Click en Ingles. + */ + @FXML + protected void menuIngles() { + ButtonType botonCambiar = new ButtonType(resourceBundle.getString("cambiar"), ButtonBar.ButtonData.OK_DONE); + ButtonType botonCancelar = new ButtonType(resourceBundle.getString("cancelar"), ButtonBar.ButtonData.CANCEL_CLOSE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("cambiarIdioma")); + dialog.setContentText(resourceBundle.getString("cambiarIdiomaMensaje")); + dialog.getDialogPane().getButtonTypes().add(botonCancelar); + dialog.getDialogPane().getButtonTypes().add(botonCambiar); + dialog.getDialogPane().setPrefSize(400, 120); + + Optional result = dialog.showAndWait(); + if (result.isPresent() && result.get() == botonCambiar) { + // Si hace click en cambiar, cambiar el idioma y reiniciar. + Locale locale = new Locale("en", "EN"); + ResourceBundle resourceBundle = ResourceBundle.getBundle("cl.cromer.estructuras.bundles.Idioma", locale); + + loadStage( + "/cl/cromer/estructuras/fxml/main.fxml", + "/cl/cromer/estructuras/css/style.css", + resourceBundle + ); + } + } + + /** + * Click en Español. + */ + @FXML + protected void menuEspanol() { + ButtonType botonCambiar = new ButtonType(resourceBundle.getString("cambiar"), ButtonBar.ButtonData.OK_DONE); + ButtonType botonCancelar = new ButtonType(resourceBundle.getString("cancelar"), ButtonBar.ButtonData.CANCEL_CLOSE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("cambiarIdioma")); + dialog.setContentText(resourceBundle.getString("cambiarIdiomaMensaje")); + dialog.getDialogPane().getButtonTypes().add(botonCancelar); + dialog.getDialogPane().getButtonTypes().add(botonCambiar); + dialog.getDialogPane().setPrefSize(400, 120); + + Optional result = dialog.showAndWait(); + if (result.isPresent() && result.get() == botonCambiar) { + // Si hace click en cambiar, cambiar el idioma y reiniciar. + Locale locale = new Locale("es", "ES"); + ResourceBundle resourceBundle = ResourceBundle.getBundle("cl.cromer.estructuras.bundles.Idioma", locale); + + loadStage( + "/cl/cromer/estructuras/fxml/main.fxml", + "/cl/cromer/estructuras/css/style.css", + resourceBundle + ); + } + } + + /** + * Click en Acerca. + */ + @FXML + protected void menuAcerca() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("acerca")); + dialog.setContentText(resourceBundle.getString("credito")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Cargar el fxml, css y titulo. + * @param title String: El titulo de la escena. + * @param fxml String: El archivo de fxml. + * @param css String: El archivo de css. + */ + private void loadStage(String title, String fxml, String css) { + Scene scene = menuBar.getScene(); + Stage stage = (Stage) scene.getWindow(); + + try { + Parent parent = FXMLLoader.load(getClass().getResource(fxml), resourceBundle); + scene.setRoot(parent); + } + catch (IOException exception) { + // Este error es fatal, hay que cerrar la aplicación. + Logs.log(Level.SEVERE, "No se pudo abrir el archivo de fxml."); + stage.close(); + } + + scene.getStylesheets().add(css); + stage.setScene(scene); + stage.setTitle(resourceBundle.getString("titulo") + " - " + title); + } + + /** + * Cargar el fxml y css. + * @param fxml String: El archivo de fxml. + * @param css String: El archivo de css. + */ + private void loadStage(String fxml, String css, ResourceBundle resourceBundle) { + Scene scene = menuBar.getScene(); + Stage stage = (Stage) scene.getWindow(); + + try { + Parent parent = FXMLLoader.load(getClass().getResource(fxml), resourceBundle); + scene.setRoot(parent); + } + catch (IOException exception) { + // Este error es fatal, hay que cerrar la aplicación. + Logs.log(Level.SEVERE, "No se pudo abrir el archivo de fxml."); + stage.close(); + } + + scene.getStylesheets().add(css); + stage.setScene(scene); + stage.setTitle(resourceBundle.getString("titulo")); + } + + /** + * Cargar el fxml, css y titulo. + * @param title String: El titulo de la escena. + * @param fxml String: El archivo de fxml. + * @param css String: El archivo de css. + */ + private void loadStage(String title, String fxml, String css, Object object) { + Scene scene = menuBar.getScene(); + Stage stage = (Stage) scene.getWindow(); + + try { + Parent parent = FXMLLoader.load(getClass().getResource(fxml), resourceBundle); + scene.setRoot(parent); + } + catch (IOException exception) { + // Este error es fatal, hay que cerrar la aplicación. + Logs.log(Level.SEVERE, "No se pudo abrir el archivo de fxml."); + stage.close(); + } + + scene.getStylesheets().add(css); + scene.setUserData(object); + stage.setScene(scene); + stage.setTitle(resourceBundle.getString("titulo") + " - " + title); + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/Pila.java b/src/cl/cromer/estructuras/Pila.java new file mode 100644 index 0000000..cd884cb --- /dev/null +++ b/src/cl/cromer/estructuras/Pila.java @@ -0,0 +1,100 @@ +package cl.cromer.estructuras; + +/** + * Crear una estructura de dato de tipo pila. + * @author Chris Cromer + */ +public class Pila { + /** + * La pila. + */ + private String pila[]; + + /** + * La cantidad de elementos en la pila. + */ + private int size; + + /** + * Inicializar. + */ + public Pila() { + pila = null; + size = 0; + } + + /** + * Devolver la cantidad de elementos en la pila. + * @return int: La cantidad de elementos. + */ + public int size() { + return size; + } + + /** + * Push un valor en la pila encima. + * @param valor int: El valor a push. + */ + public void push(int valor) { + if (this.pila != null) { + String pila[] = new String[this.pila.length + 1]; + int i; + for (i = 0; i < this.pila.length; i++) { + pila[i] = this.pila[i]; + } + pila[i] = String.valueOf(valor); + this.pila = pila; + size++; + } + else { + String pila[] = new String[1]; + pila[0] = String.valueOf(valor); + this.pila = pila; + size++; + } + } + + /** + * Pop un valor de encima de la pila. + * @return boolean: Verdad si fue exitoso. + */ + public boolean pop() { + if (this.pila != null && size() > 0) { + String pila[] = new String[this.pila.length -1]; + System.arraycopy(this.pila, 0, pila, 0, pila.length); + this.pila = pila; + size--; + return true; + } + else { + return false; + } + } + + /** + * Peek al valor que está encima de la pila. + * @return int: El valor que está encima de la pila. + */ + public int peek() { + if (pila != null && size() > 0) { + return Integer.valueOf(pila[pila.length -1]); + } + else { + return Integer.MIN_VALUE; + } + } + + /** + * Devolver el valor que está en un indice de la pila. + * @param indice int: El indice que desea devolver. + * @return String: El valor que está guardado en el indice. + */ + public String getIndice(int indice) { + if (indice >= 0 && indice < pila.length) { + return pila[indice]; + } + else { + return null; + } + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/PilaController.java b/src/cl/cromer/estructuras/PilaController.java new file mode 100644 index 0000000..3e2a376 --- /dev/null +++ b/src/cl/cromer/estructuras/PilaController.java @@ -0,0 +1,236 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.layout.VBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; +import java.util.logging.Level; + +/** + * Esta clase es para controlar todos la interfaz de Pila. + * @author Chris Cromer + */ +public class PilaController implements Initializable { + /** + * La caja para ingresar textos. + */ + @FXML private TextFieldLimited valorPila; + + /** + * Donde poner el contenido de array. + */ + @FXML private VBox contenidoPila; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoPila; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * La pila usado en la aplicación. + */ + private Pila pila; + + /** + * Grafico rectangulos. + */ + private Grafico grafico; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + pila = new Pila(); + + scene = null; + Colores colores = new Colores(); + + for (int i = 9; i >= 0; i--) { + contenidoPila.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i))); + colores.siguinteColor(); + } + } + + /** + * Llenar la pila con numeros al azar. + */ + @FXML + protected void botonLlenar() { + if (scene == null) { + scene = contenidoPila.getScene(); + grafico = new Grafico(scene); + } + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = pila.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + pila.push(numero); + } + generarGrafico(); + } + + /** + * Vaciar la pila de todos los valores. + */ + @FXML + protected void botonVaciar() { + if (scene == null) { + scene = contenidoPila.getScene(); + grafico = new Grafico(scene); + } + + pila = new Pila(); + generarGrafico(); + } + + /** + * Push un valor a la pila y mostrar el codigo en la pantalla. + */ + @FXML + protected void botonPush() { + if (scene == null) { + scene = contenidoPila.getScene(); + grafico = new Grafico(scene); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/pila/push")).useDelimiter("\\Z").next(); + codigoPila.setText(codigoTexto); + + if (valorPila.getText() != null && !valorPila.getText().trim().equals("")) { + try { + if (pila.size() < 10) { + pila.push(Integer.valueOf(valorPila.getText())); + generarGrafico(); + } + else { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("pilaLlena")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + } + catch (NumberFormatException exception) { + // El error no es fatal, sigue + Logs.log(Level.WARNING, "No es tipo int."); + errorNoValor(); + } + } + else { + errorNoValor(); + } + } + + /** + * Pop un valor de la pila si existe y mostrar el codigo en la pantalla. + */ + @FXML + protected void botonPop() { + if (scene == null) { + scene = contenidoPila.getScene(); + grafico = new Grafico(scene); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/pila/pop")).useDelimiter("\\Z").next(); + codigoPila.setText(codigoTexto); + + if (pila.size() > 0) { + pila.pop(); + generarGrafico(); + } + else { + errorVacia(); + } + } + + /** + * Peek a ver si existe un elemento en la pila y mostrar el codigo en la pantalla + * Si existe un valor destacarlo. + */ + @FXML + protected void botonPeek() { + if (scene == null) { + scene = contenidoPila.getScene(); + grafico = new Grafico(scene); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/pila/peek")).useDelimiter("\\Z").next(); + codigoPila.setText(codigoTexto); + + int encontrado = pila.peek(); + if (encontrado != Integer.MIN_VALUE) { + generarGrafico(); + grafico.destacer(pila.size() - 1, "rectangulo"); + } + else { + errorVacia(); + } + } + + /** + * Se muestra un error si la persona no ingresa un valor en el TextField. + */ + private void errorNoValor() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("pilaNoValor")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Error cuando la pila está vacía. + */ + private void errorVacia() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("pilaVacia")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + grafico.removerDestacar(); + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(pila.getIndice(i)); + } + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/SeleccionController.java b/src/cl/cromer/estructuras/SeleccionController.java new file mode 100644 index 0000000..a4bf19b --- /dev/null +++ b/src/cl/cromer/estructuras/SeleccionController.java @@ -0,0 +1,174 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.layout.HBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; + +/** + * Esta clase es para controlar todos la interfaz de Selección. + * @author Chris Cromer + */ +public class SeleccionController implements Initializable { + /** + * Donde poner el contenido de array. + */ + @FXML private HBox contenidoSeleccion; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoSeleccion; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * El array usado en la aplicación. + */ + private Array array; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + scene = null; + + Colores colores = new Colores(); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + array = new Array(10); + array.setOrdered(true); + + for (int i = 0; i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + contenidoSeleccion.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i), String.valueOf(numero))); + colores.siguinteColor(); + } + } + + /** + * Crear un array nuevo. + */ + @FXML + protected void botonNuevo() { + if (scene == null) { + initializeScene(); + } + + array = new Array(10); + array.setOrdered(true); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = array.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + } + generarGrafico(); + } + + /** + * Ordenarlo paso por paso. + */ + @FXML + protected void botonPaso() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/seleccion/ordenar")).useDelimiter("\\Z").next(); + codigoSeleccion.setText(codigoTexto); + + if (!array.seleccion(true)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Ordenarlo completamente. + */ + @FXML + protected void botonCorrer() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/seleccion/ordenar")).useDelimiter("\\Z").next(); + codigoSeleccion.setText(codigoTexto); + + if (!array.seleccion(false)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Se muestra un error si el array ya está ordenado. + */ + private void errorYaOrdenado() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("seleccionYaOrdenado")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Crear el array de temaño 10. + */ + private void initializeScene() { + scene = contenidoSeleccion.getScene(); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(array.getIndice(i)); + } + } +} diff --git a/src/cl/cromer/estructuras/ShellController.java b/src/cl/cromer/estructuras/ShellController.java new file mode 100644 index 0000000..2424370 --- /dev/null +++ b/src/cl/cromer/estructuras/ShellController.java @@ -0,0 +1,174 @@ +package cl.cromer.estructuras; + +import javafx.fxml.FXML; +import javafx.fxml.Initializable; +import javafx.scene.Scene; +import javafx.scene.control.ButtonBar; +import javafx.scene.control.ButtonType; +import javafx.scene.control.Dialog; +import javafx.scene.layout.HBox; +import javafx.scene.text.Text; + +import java.net.URL; +import java.util.Random; +import java.util.ResourceBundle; +import java.util.Scanner; + +/** + * Esta clase es para controlar todos la interfaz de Shell. + * @author Chris Cromer + */ +public class ShellController implements Initializable { + /** + * Donde poner el contenido de array. + */ + @FXML private HBox contenidoSeleccion; + + /** + * Donde va el codigo a mostrar a la pantalla. + */ + @FXML private Text codigoSeleccion; + + /** + * La escena donde está cosas graficas. + */ + private Scene scene; + + /** + * Donde está guardado los idiomas. + */ + private ResourceBundle resourceBundle; + + /** + * El array usado en la aplicación. + */ + private Array array; + + /** + * Inicializar todos los datos y dibujar las graficas. + * @param location URL: El URL de fxml en uso. + * @param resourceBundle ResourceBundle: Tiene datos de idioma. + */ + @Override + public void initialize(URL location, ResourceBundle resourceBundle) { + this.resourceBundle = resourceBundle; + + scene = null; + + Colores colores = new Colores(); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + array = new Array(10); + array.setOrdered(true); + + for (int i = 0; i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + contenidoSeleccion.getChildren().addAll(Grafico.crearCaja(colores, String.valueOf(i), String.valueOf(numero))); + colores.siguinteColor(); + } + } + + /** + * Crear un array nuevo. + */ + @FXML + protected void botonNuevo() { + if (scene == null) { + initializeScene(); + } + + array = new Array(10); + array.setOrdered(true); + + Random random = new Random(); + int maximo = 99; + int minimo = 0; + int rango = maximo - minimo + 1; + + for (int i = array.size(); i < 10; i++) { + int numero = random.nextInt(rango) + minimo; + while (array.buscar(numero) != -1) { + numero = random.nextInt(rango) + minimo; + } + array.insertar(numero); + } + generarGrafico(); + } + + /** + * Ordenarlo paso por paso. + */ + @FXML + protected void botonPaso() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/seleccion/ordenar")).useDelimiter("\\Z").next(); + codigoSeleccion.setText(codigoTexto); + + if (!array.seleccion(true)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Ordenarlo completamente. + */ + @FXML + protected void botonCorrer() { + if (scene == null) { + initializeScene(); + } + + // Mostrar el codigo + String codigoTexto = new Scanner(getClass().getResourceAsStream("/cl/cromer/estructuras/code/seleccion/ordenar")).useDelimiter("\\Z").next(); + codigoSeleccion.setText(codigoTexto); + + if (!array.seleccion(false)) { + errorYaOrdenado(); + } + + generarGrafico(); + } + + /** + * Se muestra un error si el array ya está ordenado. + */ + private void errorYaOrdenado() { + ButtonType botonCerrar = new ButtonType(resourceBundle.getString("cerrar"), ButtonBar.ButtonData.OK_DONE); + Dialog dialog = new Dialog<>(); + dialog.setTitle(resourceBundle.getString("error")); + dialog.setContentText(resourceBundle.getString("seleccionYaOrdenado")); + dialog.getDialogPane().getButtonTypes().add(botonCerrar); + dialog.show(); + } + + /** + * Crear el array de temaño 10. + */ + private void initializeScene() { + scene = contenidoSeleccion.getScene(); + } + + /** + * Poner los valores en el grafico. + */ + private void generarGrafico() { + for (int i = 0; i < 10; i++) { + Text text = (Text) scene.lookup("#caja_" + String.valueOf(i)); + text.setText(array.getIndice(i)); + } + } +} diff --git a/src/cl/cromer/estructuras/TextFieldLimited.java b/src/cl/cromer/estructuras/TextFieldLimited.java new file mode 100644 index 0000000..2c84db2 --- /dev/null +++ b/src/cl/cromer/estructuras/TextFieldLimited.java @@ -0,0 +1,155 @@ +package cl.cromer.estructuras; + +import com.sun.javafx.css.converters.SizeConverter; +import javafx.beans.property.IntegerProperty; +import javafx.css.CssMetaData; +import javafx.css.Styleable; +import javafx.css.StyleableIntegerProperty; +import javafx.css.StyleableProperty; +import javafx.scene.control.TextField; +import javafx.scene.shape.Shape; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Crear un TextField especial que tiene un maximo de digitos que puede ingresar. Se extiene a TextField. + * @author Chris Cromer + */ +public class TextFieldLimited extends TextField { + /** + * La cantidad maxima de caracters permitidas en el TextFieldLimited + */ + private IntegerProperty maxLength; + + /** + * Llamar a TextField. + */ + public TextFieldLimited() { + super(); + } + + /** + * Reemplazar el texto basado en cambios de teclado, no deja ingresar mas text si length es mayor al maximo. + * @param start int: Donde empece el cambio. + * @param end int: Donde termina. + * @param text String: Texto a cambiar. + */ + @Override + public void replaceText(int start, int end, String text) { + if (getMaxLength() != 0) { + if (text.equals("")) { + super.replaceText(start, end, text); + } + else if (getText().length() < getMaxLength()) { + super.replaceText(start, end, text); + } + } + else { + super.replaceText(start, end, text); + } + } + + /** + * Reemplazar un selección de texto. + * @param text String: El texto a reemplazar. + */ + @Override + public void replaceSelection(String text) { + if (getMaxLength() != 0) { + if (text.equals("")) { + super.replaceSelection(text); + } + else if (getText().length() < getMaxLength()) { + if (text.length() > getMaxLength() - getText().length()) { + text = text.substring(0, getMaxLength() - getText().length()); + } + super.replaceSelection(text); + } + } + else { + super.replaceSelection(text); + } + } + + /** + * Asignar un valor maximo de caracters permitidio en el TextFieldLimited. + * @param value int: La cantidad maxima. + */ + public final void setMaxLength(int value) { + if (maxLength != null || value > 0) { + maxLengthProperty().set(value); + } + } + + /** + * Devolver la cantidad maxima si está asignado. + * @return int: Cantidad de caracters. + */ + public final int getMaxLength() { + return maxLength == null ? 0 : maxLength.get(); + } + + /** + * JavaFX FXML field property por tamaño maximo + * @return IntegerProperty: Property. + */ + public final IntegerProperty maxLengthProperty() { + if (maxLength == null) { + maxLength = new StyleableIntegerProperty() { + + @Override + public CssMetaData getCssMetaData() { + return TextFieldLimited.StyleableProperties.MAX_LENGTH; + } + + @Override + public Object getBean() { + return TextFieldLimited.this; + } + + @Override + public String getName() { + return "maxLength"; + } + }; + } + return maxLength; + } + + /** + * CSS por FXML con un maximo tamaño + */ + private static class StyleableProperties { + private static final CssMetaData MAX_LENGTH = + new CssMetaData("-fx-max-length", SizeConverter.getInstance(), 0) { + @Override + public boolean isSettable(TextFieldLimited node) { + return node.maxLength == null || !node.maxLength.isBound(); + } + + @Override + public StyleableProperty getStyleableProperty(TextFieldLimited node) { + return (StyleableProperty) node.maxLengthProperty(); + } + + }; + + private static final List> STYLEABLES; + + static { + final List> styleables = new ArrayList<>(Shape.getClassCssMetaData()); + styleables.add(MAX_LENGTH); + STYLEABLES = Collections.unmodifiableList(styleables); + } + } + + /** + * Lista de estilos aplicable. + * @return List: La lista de estilos. + */ + public static List> getClassCssMetaData() { + return TextFieldLimited.StyleableProperties.STYLEABLES; + } +} diff --git a/src/cl/cromer/estructuras/bundles/Idioma_en.properties b/src/cl/cromer/estructuras/bundles/Idioma_en.properties new file mode 100644 index 0000000..60b9cdf --- /dev/null +++ b/src/cl/cromer/estructuras/bundles/Idioma_en.properties @@ -0,0 +1,86 @@ +titulo=Data Structures +tituloArraySimple=Simple Array +tituloArrayOrdenado=Ordered Array +tituloPila=Stack +tituloCola=Queue +tituloBurbuja=Bubble +tituloInsercion=Insertion +tituloSeleccion=Selection +tituloShell=Shell + +estructuras=Structures +array=Array +arraySimple=Simple +arrayOrdenado=Ordered +ordenamiento=Sort +burbuja=Bubble +insercion=Insertion +seleccion=Selection +shell=Shell +listaEnlazada=Linked List +listaSimple=Simple +listaCircular=Circular +doblementeEnlazada=Double Linked +pila=Stack +cola=Queue +arboles=Tree +general=General +binario=Binary +busquedaBinario=Binary Search +AVL=AVL +rojoNegro=Red-Black +bTree=B-Tree +grafos=Graphs +dirigidos=Directed +noDirigidos=Undirected +tablaHash=Hash Table + +idioma=Language +ingles=English +espanol=Spanish + +cambiarIdioma=Change Language +cambiarIdiomaMensaje=To change the language the program must be restarted.\n\nAre you sure you wish the restart? + +ayuda=Help +acerca=About + +credito=Made by Christopher Cromer(chris@cromer.cl)\nCivil Engineering in Computer Science\nUniversity of the B\u00EDo B\u00EDo + +cambiar=Change +cancelar=Cancel +cerrar=Close +error=Error + +llenar=Fill +vaciar=Empty +insertar=Insert +eliminar=Delete +buscar=Search +push=Push +pop=Pop +peek=Peek +nuevo=New +paso=Step +correr=Run + +arrayLleno=Value not inserted because array is full. +arrayValorExiste=Value already exists. +arrayNoEsta=Value does not exist. +arrayNoValor=Please input a numeric value. + +burbujaYaOrdenado=The array is already sorted. + +insercionYaOrdenado=The array is already sorted. + +seleccionYaOrdenado=The array is already sorted. + +shellYaOrdenado=The array is already sorted. + +pilaLlena=Value not inserted because the stack is full. +pilaVacia=The stack is empty. +pilaNoValor=Please input a numeric value. + +colaLlena=Value not inserted because the queue is full. +colaVacia=The queue is empty. +colaNoValor=Please input a numeric value. \ No newline at end of file diff --git a/src/cl/cromer/estructuras/bundles/Idioma_es.properties b/src/cl/cromer/estructuras/bundles/Idioma_es.properties new file mode 100644 index 0000000..cee58b5 --- /dev/null +++ b/src/cl/cromer/estructuras/bundles/Idioma_es.properties @@ -0,0 +1,86 @@ +titulo=Estructuras de Datos +tituloArraySimple=Array Simple +tituloArrayOrdenado=Array Ordenado +tituloPila=Pila +tituloCola=Cola +tituloBurbuja=Burbuja +tituloInsercion=Inserci\u00F3n +tituloSeleccion=Selecci\u00F3n +tutuloShell=Shell + +estructuras=Estructuras +array=Array +arraySimple=Simple +arrayOrdenado=Ordenado +ordenamiento=Ordenamiento +burbuja=Burbuja +insercion=Inserci\u00F3n +seleccion=Seleci\u00F3n +shell=Shell +listaEnlazada=Lista Enlazada +listaSimple=Simple +listaCircular=Circular +doblementeEnlazada=Doblemente Enlazada +pila=Pila +cola=Cola +arboles=Arbol +general=General +binario=Binario +busquedaBinario=Busqueda Binaria +AVL=AVL +rojoNegro=Rojo-Negro +bTree=B-Tree +grafos=Grafo +dirigidos=Dirigido +noDirigidos=No Dirigido +tablaHash=Tabla Hash + +idioma=Idioma +ingles=Ingl\u00E9s +espanol=Espa\u00F1ol + +cambiarIdioma=Cambiar Idioma +cambiarIdiomaMensaje=Para cambiar el idioma el programa debe reiniciarse.\n\nUsted est\u00E1 seguro que desea reiniciar? + +ayuda=Ayuda +acerca=Acerca + +credito=Construido por Christopher Cromer\nIngenier\u00EDa Civil en Inform\u00E1tica\nUniversidad del B\u00EDo B\u00EDo + +cambiar=Cambiar +cancelar=Cancelar +cerrar=Cerrar +error=Error + +vaciar=Vaciar +llenar=Llenar +insertar=Insertar +eliminar=Eliminar +buscar=Buscar +push=Push +pop=Pop +peek=Peek +nuevo=Nuevo +paso=Paso +correr=Correr + +arrayLleno=Valor no fue insertado porque el array est\u00E1 lleno. +arrayValorExiste=El valor ya existe. +arrayNoEsta=El valor no existe. +arrayNoValor=Ingresar un valor num\u00E9rico por favor. + +burbujaYaOrdenado=El array ya est\u00E1 ordenado. + +insercionYaOrdenado=El array ya est\u00E1 ordenado. + +seleccionYaOrdenado=El array ya est\u00E1 ordenado. + +shellYaOrdenado=El array ya est\u00E1 ordenado. + +pilaLlena=Valor no fue insertado porque la pila est\u00E1 llena. +pilaVacia=La pila est\u00E1 vac\u00EDa. +pilaNoValor=Ingresar un valor num\u00E9rico por favor. + +colaLlena=Valor no fue insertado porque la cola est\u00E1 llena. +colaVacia=La cola est\u00E1 vac\u00EDa. +colaNoValor=Ingresar un valor num\u00E9rico por favor. \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/arrayOrdenado/buscar b/src/cl/cromer/estructuras/code/arrayOrdenado/buscar new file mode 100644 index 0000000..d0131e7 --- /dev/null +++ b/src/cl/cromer/estructuras/code/arrayOrdenado/buscar @@ -0,0 +1,10 @@ +public int buscar(int valor) { + for (int i = 0; i < array.length; i++) { + if (array[i] != 0 && array[i] == valor) { + // Se encontró + return i; + } + } + // No se encontró + return -1; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/arrayOrdenado/eliminar b/src/cl/cromer/estructuras/code/arrayOrdenado/eliminar new file mode 100644 index 0000000..be88b41 --- /dev/null +++ b/src/cl/cromer/estructuras/code/arrayOrdenado/eliminar @@ -0,0 +1,18 @@ +public boolean eliminar(int valor) { + boolean borrado = false; + for (int i = 0; i < array.length; i++) { + if (array[i] != 0 && array[i] == valor) { + // Eliminar el valor + array[i] = 0; + borrado=true; + for (int j = i; j < array.length; j++) { + if (j != array.length - 1) { + // Correr la array hacia arriba + array[j] = array[j + 1]; + } + } + array[array.length-1] = 0; + } + } + return borrado; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/arrayOrdenado/insertar b/src/cl/cromer/estructuras/code/arrayOrdenado/insertar new file mode 100644 index 0000000..318dd33 --- /dev/null +++ b/src/cl/cromer/estructuras/code/arrayOrdenado/insertar @@ -0,0 +1,13 @@ +public boolean insertar(int valor) { + for (int i = 0; i < array.length; i++) { + if (array[i] == 0) { + array[i] = valor; + return true; + } + else if (array[i] == valor) { + // Ya existe el valor en el array + return false; + } + } + return false; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/arraySimple/buscar b/src/cl/cromer/estructuras/code/arraySimple/buscar new file mode 100644 index 0000000..d0131e7 --- /dev/null +++ b/src/cl/cromer/estructuras/code/arraySimple/buscar @@ -0,0 +1,10 @@ +public int buscar(int valor) { + for (int i = 0; i < array.length; i++) { + if (array[i] != 0 && array[i] == valor) { + // Se encontró + return i; + } + } + // No se encontró + return -1; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/arraySimple/eliminar b/src/cl/cromer/estructuras/code/arraySimple/eliminar new file mode 100644 index 0000000..f41b04d --- /dev/null +++ b/src/cl/cromer/estructuras/code/arraySimple/eliminar @@ -0,0 +1,12 @@ +public boolean eliminar(int valor) { + boolean borrado = false; + for (int i = 0; i < array.length; i++) { + if (array[i] != 0 && array[i] == valor) { + // Eliminar el valor + array[i] = 0; + borrado=true; + break; + } + } + return borrado; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/arraySimple/insertar b/src/cl/cromer/estructuras/code/arraySimple/insertar new file mode 100644 index 0000000..318dd33 --- /dev/null +++ b/src/cl/cromer/estructuras/code/arraySimple/insertar @@ -0,0 +1,13 @@ +public boolean insertar(int valor) { + for (int i = 0; i < array.length; i++) { + if (array[i] == 0) { + array[i] = valor; + return true; + } + else if (array[i] == valor) { + // Ya existe el valor en el array + return false; + } + } + return false; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/burbuja/ordenar b/src/cl/cromer/estructuras/code/burbuja/ordenar new file mode 100644 index 0000000..b4d2136 --- /dev/null +++ b/src/cl/cromer/estructuras/code/burbuja/ordenar @@ -0,0 +1,13 @@ +public void burbuja() { + for (int i = elementos - 1; i > 1; i--) { + for(j = 0; in < i; j++) { + // Si están fuera del orden + if (array[j] > array[j+1]) { + // Intercambiar valores + int temp = array[j]; + array[j] = array[j+1]; + array[j+1] = temp; + } + } + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/cola/peek b/src/cl/cromer/estructuras/code/cola/peek new file mode 100644 index 0000000..0854454 --- /dev/null +++ b/src/cl/cromer/estructuras/code/cola/peek @@ -0,0 +1,4 @@ +public int peek() { + // Devolver el valor en el primer indice + return this.pila[primer]; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/cola/pop b/src/cl/cromer/estructuras/code/cola/pop new file mode 100644 index 0000000..3ba1e45 --- /dev/null +++ b/src/cl/cromer/estructuras/code/cola/pop @@ -0,0 +1,6 @@ +public void pop() { + // Borrar el valor que está al prinicipio. + this.pila[primer] = 0; + // Cambiar el primer nivel de la cola. + primer++; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/cola/push b/src/cl/cromer/estructuras/code/cola/push new file mode 100644 index 0000000..c453fda --- /dev/null +++ b/src/cl/cromer/estructuras/code/cola/push @@ -0,0 +1,6 @@ +public void push(int valor) { + // Sumar el final. + final++; + // Insertar el valor + this.pila[final] = valor; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/insercion/ordenar b/src/cl/cromer/estructuras/code/insercion/ordenar new file mode 100644 index 0000000..0c7eaaf --- /dev/null +++ b/src/cl/cromer/estructuras/code/insercion/ordenar @@ -0,0 +1,14 @@ +public void insercion() { + for (int i = 1; i < elementos; i++) { + // Guardar el elemento en un variable temporario. + int temp = array[i]; + int j = i; + // Mover los valores hasta que hay una mas pequeño. + while (j > 0 && array[j-1] >= temp) { + array[j] = array[j-1]; + --j; + } + // Poner el valor temporario despues de los valores mas pequeños. + array[j] = temp; + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/pila/peek b/src/cl/cromer/estructuras/code/pila/peek new file mode 100644 index 0000000..0dcd790 --- /dev/null +++ b/src/cl/cromer/estructuras/code/pila/peek @@ -0,0 +1,4 @@ +public int peek() { + // Devolver el valor encima + return this.pila[encima]; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/pila/pop b/src/cl/cromer/estructuras/code/pila/pop new file mode 100644 index 0000000..97dbfe4 --- /dev/null +++ b/src/cl/cromer/estructuras/code/pila/pop @@ -0,0 +1,6 @@ +public void pop() { + // Borrar el valor que está encima. + this.pila[encima] = 0; + // Restar el nivel de la pila. + encima--; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/pila/push b/src/cl/cromer/estructuras/code/pila/push new file mode 100644 index 0000000..375870a --- /dev/null +++ b/src/cl/cromer/estructuras/code/pila/push @@ -0,0 +1,6 @@ +public void push(int valor) { + // Sumar el nivel de la pila + encima++; + // Insertar el valor + this.pila[encima] = valor; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/code/seleccion/ordenar b/src/cl/cromer/estructuras/code/seleccion/ordenar new file mode 100644 index 0000000..c5b646f --- /dev/null +++ b/src/cl/cromer/estructuras/code/seleccion/ordenar @@ -0,0 +1,13 @@ +public void seleccion() { + for (int i = 0; i < elementos - 1; i++) { + int minimo = i; + for (int j = i + 1; j < elementos; j++) { + if (array[j] < array[minimo]) { + minimo = j; + } + } + int temp = array[i]; + array[i] = array[minimo]; + array[minimo] = temp; + } +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/css/style.css b/src/cl/cromer/estructuras/css/style.css new file mode 100644 index 0000000..3f7b79a --- /dev/null +++ b/src/cl/cromer/estructuras/css/style.css @@ -0,0 +1,21 @@ +.text { + -fx-font-family: "Arial"; + -fx-font-size: 14; +} + +.menu-bar { + -fx-background-color: #aeb5ba, linear-gradient(to bottom, #ecf4fa 0%, #ced4d9 100%); + -fx-background-insets: 0, 0 0 1 0; +} + +.menu-bar .menu .label { + -fx-text-fill: #2d3e4c; +} + +.text-field-limited { + -fx-max-length: 3; +} + +.scroll-pane { + -fx-background-color:transparent; +} \ No newline at end of file diff --git a/src/cl/cromer/estructuras/fxml/array.fxml b/src/cl/cromer/estructuras/fxml/array.fxml new file mode 100644 index 0000000..32783a8 --- /dev/null +++ b/src/cl/cromer/estructuras/fxml/array.fxml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + +