├── a.txt ├── CalculadoraPostfix ├── src │ ├── .idea │ │ ├── .name │ │ ├── vcs.xml │ │ ├── .gitignore │ │ ├── misc.xml │ │ └── modules.xml │ ├── out │ │ ├── production │ │ │ ├── CalculadoraPostfix │ │ │ │ ├── .idea │ │ │ │ │ ├── .name │ │ │ │ │ ├── vcs.xml │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── misc.xml │ │ │ │ │ └── modules.xml │ │ │ │ └── CalculadoraPostfix.iml │ │ │ └── .DS_Store │ │ └── .DS_Store │ ├── .DS_Store │ ├── Tests │ │ └── Screenshot 2024-01-30 225657.png │ ├── IStack.java │ ├── CalculadoraPostfix.iml │ ├── ICalculator.java │ ├── Controlador.java │ ├── StackWithVector.java │ ├── ControladorTest.java │ └── Calculadora.java ├── .DS_Store ├── design │ ├── Screenshot 2024-01-30 225509.png │ └── Screenshot 2024-01-29 at 10.23.39 PM.png ├── bin │ ├── Screenshot 2024-01-29 at 10.23.39 PM.jpg │ ├── .idea │ │ ├── vcs.xml │ │ ├── .gitignore │ │ ├── misc.xml │ │ └── modules.xml │ ├── out │ │ └── production │ │ │ └── CalculadoraPostfix │ │ │ ├── .idea │ │ │ ├── vcs.xml │ │ │ ├── .gitignore │ │ │ ├── misc.xml │ │ │ └── modules.xml │ │ │ └── CalculadoraPostfix.iml │ └── CalculadoraPostfix.iml ├── .vscode │ └── settings.json └── README.md ├── Diccionario Idiomas ├── texto.txt ├── src │ ├── IWalk.java │ ├── ITree.java │ ├── SaveInArrayListWalk.java │ ├── Association.java │ ├── TreeNode.java │ ├── BinarySearchTreeTest.java │ ├── BinarySearchTree.java │ └── DictionaryProgram.java ├── diccionario.txt ├── .vscode │ └── settings.json └── README.md ├── HDT 8 Heap ├── procesos.txt ├── src │ ├── IHeap.java │ ├── ComparadorNumeros.java │ ├── Proceso.java │ ├── TreeNode.java │ ├── Main.java │ ├── HeapUsingIterativeBinaryTreeTest.java │ └── HeapUsingIterativeBinaryTree.java ├── .vscode │ └── settings.json └── README.md ├── HDT8 Priority Queue JCF ├── procesos.txt ├── .vscode │ └── settings.json ├── README.md └── src │ ├── Proceso.java │ └── Main.java ├── Checkpoint Factory Design ├── exported_data.csv ├── exported_data.txt ├── src │ ├── IDataSource.java │ ├── Main.java │ ├── User.java │ ├── DataSourceFactory.java │ ├── Auditor.java │ ├── Faculty.java │ ├── JSONDataSource.java │ ├── Course.java │ ├── CSVDataSource.java │ ├── Student.java │ ├── TXTDataSource.java │ ├── Admin.java │ └── UniversityController.java ├── data_prueba.json ├── .vscode │ └── settings.json └── README.md ├── Hoja de Trabajo 5 ├── Hoja de Trabajo 5 Graficas Resultados y Conclusion.pdf ├── Hoja de Trabajo 5 Graficas Resultados y Conclusion.docx └── HDT5.py ├── .gitignore └── Sorts ├── ShellSort.py ├── SelectionSort.py ├── Gnomesort.py ├── QuickSort.py ├── RadixSort.py ├── heapsort.py └── MergeSort.py /a.txt: -------------------------------------------------------------------------------- 1 | 1 2 3 + - -------------------------------------------------------------------------------- /CalculadoraPostfix/src/.idea/.name: -------------------------------------------------------------------------------- 1 | Calculadora.java -------------------------------------------------------------------------------- /Diccionario Idiomas/texto.txt: -------------------------------------------------------------------------------- 1 | The woman asked me to do my homework about my town -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/CalculadoraPostfix/.idea/.name: -------------------------------------------------------------------------------- 1 | Calculadora.java -------------------------------------------------------------------------------- /HDT 8 Heap/procesos.txt: -------------------------------------------------------------------------------- 1 | vi,juan02,0 2 | ls,maria30,-20 3 | firefox,rosa20,5 4 | cat,juan02,5 -------------------------------------------------------------------------------- /HDT8 Priority Queue JCF/procesos.txt: -------------------------------------------------------------------------------- 1 | vi,juan02,0 2 | ls,maria30,-20 3 | firefox,rosa20,5 4 | cat,juan02,5 -------------------------------------------------------------------------------- /Diccionario Idiomas/src/IWalk.java: -------------------------------------------------------------------------------- 1 | public interface IWalk { 2 | 3 | void doWalk(V actualValue); 4 | } 5 | -------------------------------------------------------------------------------- /CalculadoraPostfix/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/.DS_Store -------------------------------------------------------------------------------- /CalculadoraPostfix/src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/src/.DS_Store -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/src/out/.DS_Store -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/src/out/production/.DS_Store -------------------------------------------------------------------------------- /Diccionario Idiomas/diccionario.txt: -------------------------------------------------------------------------------- 1 | house,casa,loger 2 | dog,perro,chien 3 | homework,tarea,devoirs 4 | woman,mujer,femme 5 | town,pueblo,ville 6 | yes,si,Oui -------------------------------------------------------------------------------- /Checkpoint Factory Design/exported_data.csv: -------------------------------------------------------------------------------- 1 | student1,studentpass1 2 | faculty1,facultypass1 3 | auditor1,auditorpass1 4 | admin1,adminpass1 5 | Mathematics 6 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/exported_data.txt: -------------------------------------------------------------------------------- 1 | student1,studentpass1, 2 | faculty1,facultypass1, 3 | auditor1,auditorpass1, 4 | admin1,adminpass1, 5 | Mathematics, 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/design/Screenshot 2024-01-30 225509.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/design/Screenshot 2024-01-30 225509.png -------------------------------------------------------------------------------- /CalculadoraPostfix/src/Tests/Screenshot 2024-01-30 225657.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/src/Tests/Screenshot 2024-01-30 225657.png -------------------------------------------------------------------------------- /HDT 8 Heap/src/IHeap.java: -------------------------------------------------------------------------------- 1 | interface IHeap { 2 | void Insert(P priority, V value); 3 | V remove(); 4 | boolean isEmpty(); 5 | int count(); 6 | V get(); 7 | } 8 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/Screenshot 2024-01-29 at 10.23.39 PM.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/bin/Screenshot 2024-01-29 at 10.23.39 PM.jpg -------------------------------------------------------------------------------- /CalculadoraPostfix/design/Screenshot 2024-01-29 at 10.23.39 PM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/CalculadoraPostfix/design/Screenshot 2024-01-29 at 10.23.39 PM.png -------------------------------------------------------------------------------- /Hoja de Trabajo 5/Hoja de Trabajo 5 Graficas Resultados y Conclusion.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/Hoja de Trabajo 5/Hoja de Trabajo 5 Graficas Resultados y Conclusion.pdf -------------------------------------------------------------------------------- /Hoja de Trabajo 5/Hoja de Trabajo 5 Graficas Resultados y Conclusion.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iancumes/Estructura-de-Datos/HEAD/Hoja de Trabajo 5/Hoja de Trabajo 5 Graficas Resultados y Conclusion.docx -------------------------------------------------------------------------------- /HDT 8 Heap/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /CalculadoraPostfix/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/IDataSource.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public interface IDataSource { 4 | void saveData(List data, String path); 5 | List loadData(String path); 6 | } 7 | -------------------------------------------------------------------------------- /Diccionario Idiomas/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main { 4 | 5 | 6 | public static void main(String[] args) { 7 | UniversityController.start(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /HDT8 Priority Queue JCF/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/out/production/CalculadoraPostfix/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/out/production/CalculadoraPostfix/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/CalculadoraPostfix/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/CalculadoraPostfix/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/out/production/CalculadoraPostfix/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/CalculadoraPostfix/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/out/production/CalculadoraPostfix/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/IStack.java: -------------------------------------------------------------------------------- 1 | public interface IStack{ 2 | 3 | /** 4 | * Devuelve la cantidad de elementos 5 | * @return un entero que devuelve la cantidad de elementos 6 | */ 7 | int count(); 8 | 9 | boolean isEmpty(); 10 | 11 | void push(T value); 12 | 13 | T pop(); 14 | 15 | T peek(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/CalculadoraPostfix/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Diccionario Idiomas/src/ITree.java: -------------------------------------------------------------------------------- 1 | public interface ITree { 2 | 3 | void insert(K key, V value); 4 | 5 | V find(K keyToFind); 6 | 7 | int count(); 8 | 9 | boolean isEmpty(); 10 | 11 | V remove(K key); 12 | 13 | void InOrderWalk(IWalk walk); 14 | 15 | void PreOrderWalk(IWalk walk); 16 | 17 | void PostOrderWalk(IWalk walk); 18 | } -------------------------------------------------------------------------------- /Checkpoint Factory Design/data_prueba.json: -------------------------------------------------------------------------------- 1 | {"students":[{"username":"student1","password":"studentpass1"}],"faculties":[{"username":"faculty1","password":"facultypass1"}],"courses":[{"courseName":"Mathematics","courseFaculty":{"username":"faculty1","password":"facultypass1"},"students":[]}],"auditors":[{"username":"auditor1","password":"auditorpass1"}],"admins":[{"username":"admin1","password":"adminpass1"}]} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | replay_pid* 25 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar", 6 | "c:\\Users\\Usuario\\Downloads\\jar_files (1)\\jaxb-api-2.4.0-b180830.0359.jar", 7 | "c:\\Users\\Usuario\\Downloads\\jar_files (1)\\javax.activation-api-1.2.0.jar" 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /HDT 8 Heap/src/ComparadorNumeros.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | public class ComparadorNumeros implements Comparator { 4 | 5 | @Override 6 | public int compare(Integer o1, Integer o2) { 7 | if ((int)o1 == (int)o2) 8 | return 0; 9 | else if ((int)o1 > (int)o2) 10 | return -1; 11 | else 12 | return 1; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/User.java: -------------------------------------------------------------------------------- 1 | public abstract class User { 2 | private String username; 3 | private String password; 4 | 5 | public User(String username, String password) { 6 | this.username = username; 7 | this.password = password; 8 | } 9 | 10 | public String getUsername() { 11 | return username; 12 | } 13 | 14 | public String getPassword() { 15 | return password; 16 | } 17 | } -------------------------------------------------------------------------------- /Diccionario Idiomas/src/SaveInArrayListWalk.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class SaveInArrayListWalk implements IWalk { 4 | 5 | private ArrayList listado; 6 | 7 | public SaveInArrayListWalk() { 8 | listado = new ArrayList(); 9 | } 10 | 11 | @Override 12 | public void doWalk(V actualValue) { 13 | listado.add(actualValue); 14 | } 15 | 16 | public ArrayList getListado() { 17 | return listado; 18 | } 19 | } -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/CalculadoraPostfix.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/CalculadoraPostfix.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /CalculadoraPostfix/bin/out/production/CalculadoraPostfix/CalculadoraPostfix.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/out/production/CalculadoraPostfix/CalculadoraPostfix.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/ICalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public interface ICalculator { 4 | 5 | public int add(int n1, int n2);// + 6 | public int substraction(int n1, int n2);// - 7 | public int multiplication(int n1, int n2);// * 8 | public int division(int n1, int n2) throws Exception;// / 9 | public int residue(int n1, int n2) throws Exception;// % 10 | public ArrayList read(String charactersString) throws Exception; 11 | public int solve(ArrayList elements) throws Exception; 12 | } -------------------------------------------------------------------------------- /Diccionario Idiomas/src/Association.java: -------------------------------------------------------------------------------- 1 | class Association { 2 | private String english; 3 | private String spanish; 4 | private String french; 5 | 6 | public Association(String english, String spanish, String french) { 7 | this.english = english; 8 | this.spanish = spanish; 9 | this.french = french; 10 | } 11 | 12 | public String getEnglish() { 13 | return english; 14 | } 15 | 16 | public String getSpanish() { 17 | return spanish; 18 | } 19 | 20 | public String getFrench() { 21 | return french; 22 | } 23 | } -------------------------------------------------------------------------------- /HDT 8 Heap/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Diccionario Idiomas/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/DataSourceFactory.java: -------------------------------------------------------------------------------- 1 | public class DataSourceFactory { 2 | public static final int CSV_TYPE = 0; 3 | public static final int JSON_TYPE = 1; 4 | public static final int TXT_TYPE = 2; // Agregamos un nuevo tipo para XML 5 | 6 | public static IDataSource getDataSourceInstance(int formatType) { 7 | switch (formatType) { 8 | case CSV_TYPE: 9 | return new CSVDataSource(); 10 | case JSON_TYPE: 11 | return new JSONDataSource(); 12 | case TXT_TYPE: 13 | return new TXTDataSource(); // Devuelve una instancia de TXTDataSource para el tipo TXT 14 | default: 15 | throw new IllegalArgumentException("Invalid format type"); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /HDT8 Priority Queue JCF/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /CalculadoraPostfix/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /HDT 8 Heap/src/Proceso.java: -------------------------------------------------------------------------------- 1 | public class Proceso implements Comparable { 2 | private String nombre; 3 | private String usuario; 4 | private int nice; 5 | private int priority; 6 | 7 | public Proceso(String nombre, String usuario, int nice, int priority) { 8 | this.nombre = nombre; 9 | this.usuario = usuario; 10 | this.nice = nice; 11 | this.priority = priority; 12 | } 13 | 14 | @Override 15 | public int compareTo(Proceso otro) { 16 | return Integer.compare(this.priority, otro.priority); 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | int pr = this.priority + 100; // Convertir la prioridad a un rango de 100 a 139 22 | return nombre + "," + usuario + "," + nice + ",PR = " + pr; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/Auditor.java: -------------------------------------------------------------------------------- 1 | public class Auditor extends User { 2 | public Auditor() { 3 | // Constructor predeterminado sin argumentos 4 | super("", ""); // Puedes proporcionar valores predeterminados para el nombre de usuario y la contraseña si es necesario 5 | } 6 | 7 | public Auditor(String username, String password) { 8 | super(username, password); 9 | } 10 | 11 | // Additional functionalities specific to auditor 12 | public void reviewGrades() { 13 | // Implementation for reviewing grades 14 | } 15 | 16 | public void reviewStudentPayments() { 17 | // Implementation for reviewing student payments 18 | } 19 | 20 | public void reviewFacultyPayments() { 21 | // Implementation for reviewing faculty payments 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /HDT8 Priority Queue JCF/src/Proceso.java: -------------------------------------------------------------------------------- 1 | public class Proceso implements Comparable { 2 | private String nombre; 3 | private String usuario; 4 | private int nice; 5 | private int priority; 6 | 7 | public Proceso(String nombre, String usuario, int nice, int priority) { 8 | this.nombre = nombre; 9 | this.usuario = usuario; 10 | this.nice = nice; 11 | this.priority = priority; 12 | } 13 | 14 | @Override 15 | public int compareTo(Proceso otro) { 16 | return Integer.compare(this.priority, otro.priority); 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | int pr = this.priority + 100; // Convertir la prioridad a un rango de 100 a 139 22 | return nombre + "," + usuario + "," + nice + ",PR = " + pr; 23 | } 24 | public int getPriority() { 25 | return priority; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/Faculty.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Faculty extends User { 5 | 6 | 7 | public Faculty() { 8 | super("", ""); // Constructor predeterminado con valores predeterminados o vacíos para el nombre de usuario y la contraseña 9 | } 10 | 11 | public Faculty(String username, String password ) { 12 | super(username, password); 13 | } 14 | 15 | public void enterGrades(Student student, Course course, List grades) { 16 | // Implement logic for faculty to enter grades for students 17 | } 18 | 19 | public void viewPaymentHistory() { 20 | // Implement logic for faculty to view payment history 21 | } 22 | 23 | public void collectPayment(Student student, double amount) { 24 | // Implement logic for faculty to collect payment from students 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Sorts/ShellSort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | 4 | def shell_sort(arr, ascending=True): 5 | n = len(arr) 6 | gap = n // 2 7 | while gap > 0: 8 | for i in range(gap, n): 9 | temp = arr[i] 10 | j = i 11 | while j >= gap and ((ascending and arr[j - gap] > temp) or (not ascending and arr[j - gap] < temp)): 12 | arr[j] = arr[j - gap] 13 | j -= gap 14 | arr[j] = temp 15 | gap //= 2 16 | 17 | # Imprimir la lista ordenada 18 | print("Lista ordenada:", arr) 19 | 20 | # Generar una lista aleatoria de longitud 10 21 | random_list = [random.randint(0, 10000) for _ in range(20000)] 22 | 23 | print("Lista original:", random_list) 24 | 25 | # Ordenar de forma ascendente con cProfile 26 | cProfile.run("shell_sort(random_list.copy(), True)") 27 | 28 | # Ordenar de forma descendente con cProfile 29 | cProfile.run("shell_sort(random_list.copy(), False)") 30 | -------------------------------------------------------------------------------- /Sorts/SelectionSort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | 4 | def selection_sort(arr, ascending=True): 5 | n = len(arr) 6 | for i in range(n): 7 | min_idx = i 8 | for j in range(i + 1, n): 9 | if ascending: 10 | if arr[j] < arr[min_idx]: 11 | min_idx = j 12 | else: 13 | if arr[j] > arr[min_idx]: 14 | min_idx = j 15 | arr[i], arr[min_idx] = arr[min_idx], arr[i] 16 | 17 | # Imprimir la lista ordenada 18 | print("Lista ordenada:", arr) 19 | 20 | # Generar una lista aleatoria de longitud 10 21 | random_list = [random.randint(0, 10000) for _ in range(25000)] 22 | 23 | print("Lista original:", random_list) 24 | 25 | # Ordenar de forma ascendente con cProfile 26 | cProfile.run("selection_sort(random_list.copy(), True)") 27 | 28 | # Ordenar de forma descendente con cProfile 29 | cProfile.run("selection_sort(random_list.copy(), False)") 30 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/JSONDataSource.java: -------------------------------------------------------------------------------- 1 | import com.fasterxml.jackson.core.type.TypeReference; 2 | import com.fasterxml.jackson.databind.ObjectMapper; 3 | 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | public class JSONDataSource implements IDataSource { 9 | 10 | private final ObjectMapper objectMapper; 11 | 12 | public JSONDataSource() { 13 | this.objectMapper = new ObjectMapper(); 14 | } 15 | 16 | @Override 17 | public void saveData(List data, String path) { 18 | try { 19 | objectMapper.writeValue(new File(path), data); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | @Override 26 | public List loadData(String path) { 27 | try { 28 | return objectMapper.readValue(new File(path), new TypeReference>() {}); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | return null; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Sorts/Gnomesort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | 4 | def gnome_sort(arr): 5 | index = 0 6 | n = len(arr) 7 | while index < n: 8 | if index == 0: 9 | index += 1 10 | if arr[index] >= arr[index - 1]: 11 | index += 1 12 | else: 13 | arr[index], arr[index - 1] = arr[index - 1], arr[index] 14 | index -= 1 15 | 16 | if __name__ == "__main__": 17 | # Generar una lista de números aleatorios 18 | random.seed(42) # Fijar la semilla para obtener los mismos resultados cada vez 19 | lista = [random.randint(0, 10000) for _ in range(10000)] 20 | 21 | # Mostrar la lista desordenada 22 | print("Lista desordenada:") 23 | print(lista) 24 | 25 | # Medir el tiempo de ejecución del algoritmo 26 | profiler = cProfile.Profile() 27 | profiler.enable() 28 | 29 | # Ordenar la lista utilizando Gnome Sort 30 | gnome_sort(lista) 31 | 32 | profiler.disable() 33 | 34 | # Mostrar la lista ordenada 35 | print("\nLista ordenada:") 36 | print(lista) 37 | 38 | profiler.print_stats(sort='cumtime') 39 | -------------------------------------------------------------------------------- /Sorts/QuickSort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | 4 | def quick_sort(arr, ascending=True): 5 | if len(arr) <= 1: 6 | return arr 7 | else: 8 | pivot = arr[0] 9 | less_than_pivot = [x for x in arr[1:] if x <= pivot] 10 | greater_than_pivot = [x for x in arr[1:] if x > pivot] 11 | 12 | if ascending: 13 | return quick_sort(less_than_pivot, ascending) + [pivot] + quick_sort(greater_than_pivot, ascending) 14 | else: 15 | return quick_sort(greater_than_pivot, ascending) + [pivot] + quick_sort(less_than_pivot, ascending) 16 | 17 | # Generar una lista aleatoria de longitud 10 18 | random_list = [random.randint(0, 10000) for _ in range(15000)] 19 | 20 | print("Lista original:", random_list) 21 | 22 | # Ordenar de forma ascendente 23 | cProfile.run("sorted_list = quick_sort(random_list.copy(), True)") 24 | print("Lista ordenada de forma ascendente:", sorted_list) 25 | 26 | # Ordenar de forma descendente 27 | cProfile.run("sorted_list_desc = quick_sort(random_list.copy(), False)") 28 | print("Lista ordenada de forma descendente:", sorted_list_desc) 29 | -------------------------------------------------------------------------------- /HDT 8 Heap/src/TreeNode.java: -------------------------------------------------------------------------------- 1 | 2 | public class TreeNode { 3 | 4 | private P _priority; 5 | private V _value; 6 | TreeNode _parent; 7 | TreeNode _left; 8 | TreeNode _right; 9 | 10 | public TreeNode(P priority, V value) { 11 | set_priority(priority); 12 | set_value(value); 13 | set_parent(null); 14 | set_left(null); 15 | set_right(null); 16 | } 17 | 18 | public P get_priority() { 19 | return _priority; 20 | } 21 | public void set_priority(P _priority) { 22 | this._priority = _priority; 23 | } 24 | public V get_value() { 25 | return _value; 26 | } 27 | public void set_value(V _value) { 28 | this._value = _value; 29 | } 30 | public TreeNode get_parent() { 31 | return _parent; 32 | } 33 | public void set_parent(TreeNode _parent) { 34 | this._parent = _parent; 35 | } 36 | public TreeNode get_left() { 37 | return _left; 38 | } 39 | public void set_left(TreeNode _left) { 40 | this._left = _left; 41 | } 42 | public TreeNode get_right() { 43 | return _right; 44 | } 45 | public void set_right(TreeNode _right) { 46 | this._right = _right; 47 | } 48 | 49 | 50 | 51 | } -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/Course.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Course { 5 | private String courseName; 6 | private Faculty courseFaculty; 7 | private List students; 8 | 9 | public Course() { 10 | // Constructor predeterminado sin argumentos 11 | this.courseName = ""; 12 | this.courseFaculty = null; 13 | this.students = new ArrayList<>(); 14 | } 15 | 16 | public Course(String courseName, Faculty courseFaculty) { 17 | this.courseName = courseName; 18 | this.courseFaculty = courseFaculty; 19 | this.students = new ArrayList<>(); 20 | } 21 | 22 | public String getCourseName() { 23 | return courseName; 24 | } 25 | 26 | public Faculty getCourseFaculty() { 27 | return courseFaculty; 28 | } 29 | 30 | public void setCourseFaculty(Faculty faculty) { 31 | this.courseFaculty = faculty; 32 | } 33 | 34 | public List getStudents() { 35 | return students; 36 | } 37 | 38 | public void addStudent(Student student) { 39 | students.add(student); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/Controlador.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Controlador implements ICalculator{ 4 | 5 | public Controlador() { 6 | } 7 | 8 | @Override 9 | public int add(int n1, int n2) { 10 | int n5 = n1 + n2; 11 | return n5; 12 | } 13 | 14 | @Override 15 | public int substraction(int n1, int n2) { 16 | int n5 = n1 - n2; 17 | return n5; 18 | } 19 | 20 | @Override 21 | public int multiplication(int n1, int n2) { 22 | int n5 = n1 * n2; 23 | return n5; 24 | } 25 | 26 | @Override 27 | public int division(int n1, int n2) throws Exception { 28 | int n5 = n1 / n2; 29 | return n5; 30 | } 31 | 32 | @Override 33 | public int residue(int n1, int n2) throws Exception { 34 | return 0; 35 | } 36 | 37 | @Override 38 | public ArrayList read(String charactersString) throws Exception { 39 | return null; 40 | } 41 | 42 | @Override 43 | public int solve(ArrayList elements) throws Exception { 44 | return 0; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/StackWithVector.java: -------------------------------------------------------------------------------- 1 | import java.util.Vector; 2 | 3 | public class StackWithVector implements IStack { 4 | 5 | private Vector internalVector; 6 | 7 | public StackWithVector() { 8 | internalVector = new Vector<>(); 9 | } 10 | 11 | @Override 12 | public int count() { 13 | return internalVector.size(); 14 | } 15 | 16 | @Override 17 | public boolean isEmpty() { 18 | return internalVector.isEmpty(); 19 | } 20 | 21 | @Override 22 | public void push(String value) { 23 | internalVector.add(value); 24 | } 25 | 26 | @Override 27 | public String pop() { 28 | String tempValue = null; 29 | if (!internalVector.isEmpty()) { 30 | tempValue = internalVector.remove(internalVector.size() - 1); 31 | } 32 | return tempValue; 33 | } 34 | 35 | @Override 36 | public String peek() { 37 | String tempValue = null; 38 | if (!internalVector.isEmpty()) { 39 | tempValue = internalVector.get(internalVector.size() - 1); 40 | } 41 | return tempValue; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Diccionario Idiomas/src/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | 3 | private K key; 4 | private V value; 5 | private TreeNode left; 6 | private TreeNode right; 7 | private TreeNode parent; 8 | 9 | public TreeNode(K key, V value) { 10 | this.key = key; 11 | this.value = value; 12 | parent = null; 13 | left = null; 14 | right = null; 15 | } 16 | 17 | public K getKey() { 18 | return key; 19 | } 20 | 21 | public void setKey(K key) { 22 | this.key = key; 23 | } 24 | 25 | public V getValue() { 26 | return value; 27 | } 28 | 29 | public void setValue(V value) { 30 | this.value = value; 31 | } 32 | 33 | public TreeNode getLeft() { 34 | return left; 35 | } 36 | 37 | public void setLeft(TreeNode left) { 38 | this.left = left; 39 | } 40 | 41 | public TreeNode getRight() { 42 | return right; 43 | } 44 | 45 | public void setRight(TreeNode right) { 46 | this.right = right; 47 | } 48 | 49 | public TreeNode getParent() { 50 | return parent; 51 | } 52 | 53 | public void setParent(TreeNode parent) { 54 | this.parent = parent; 55 | } 56 | 57 | 58 | } -------------------------------------------------------------------------------- /Sorts/RadixSort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | 4 | def counting_sort(arr, exp, ascending=True): 5 | n = len(arr) 6 | output = [0] * n 7 | count = [0] * 10 8 | 9 | for i in range(n): 10 | index = arr[i] // exp 11 | count[index % 10] += 1 12 | 13 | if ascending: 14 | for i in range(1, 10): 15 | count[i] += count[i - 1] 16 | else: 17 | for i in range(8, -1, -1): 18 | count[i] += count[i + 1] 19 | 20 | i = n - 1 21 | while i >= 0: 22 | index = arr[i] // exp 23 | output[count[index % 10] - 1] = arr[i] 24 | count[index % 10] -= 1 25 | i -= 1 26 | 27 | for i in range(n): 28 | arr[i] = output[i] 29 | 30 | def radix_sort(arr, ascending=True): 31 | max_val = max(arr) 32 | exp = 1 33 | while max_val // exp > 0: 34 | counting_sort(arr, exp, ascending) 35 | exp *= 10 36 | 37 | # Imprimir la lista ordenada 38 | print("Lista ordenada:", arr) 39 | 40 | # Generar una lista aleatoria de longitud 10 41 | random_list = [random.randint(0, 10000) for _ in range(20000)] 42 | 43 | print("Lista original:", random_list) 44 | 45 | # Ordenar de forma ascendente con cProfile 46 | cProfile.run("radix_sort(random_list.copy(), True)") 47 | 48 | # Ordenar de forma descendente con cProfile 49 | cProfile.run("radix_sort(random_list.copy(), False)") 50 | -------------------------------------------------------------------------------- /Sorts/heapsort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | 4 | def heapify(arr, n, i, ascending=True): 5 | largest = i 6 | l = 2 * i + 1 7 | r = 2 * i + 2 8 | 9 | if l < n and ((ascending and arr[l] > arr[largest]) or (not ascending and arr[l] < arr[largest])): 10 | largest = l 11 | 12 | if r < n and ((ascending and arr[r] > arr[largest]) or (not ascending and arr[r] < arr[largest])): 13 | largest = r 14 | 15 | if largest != i: 16 | arr[i], arr[largest] = arr[largest], arr[i] 17 | heapify(arr, n, largest, ascending) 18 | 19 | def heap_sort(arr, ascending=True): 20 | n = len(arr) 21 | 22 | # Construir el max-heap. 23 | for i in range(n // 2 - 1, -1, -1): 24 | heapify(arr, n, i, ascending) 25 | 26 | # Extraer elementos uno por uno del heap 27 | for i in range(n - 1, 0, -1): 28 | arr[i], arr[0] = arr[0], arr[i] 29 | heapify(arr, i, 0, ascending) 30 | 31 | # Imprimir la lista ordenada 32 | print("Lista ordenada:", arr) 33 | 34 | # Generar una lista aleatoria de longitud 10 35 | random_list = [random.randint(0, 10000) for _ in range(7500)] 36 | 37 | print("Lista original:", random_list) 38 | 39 | # Ordenar de forma ascendente con cProfile 40 | cProfile.run("heap_sort(random_list.copy(), True)") 41 | 42 | # Ordenar de forma descendente con cProfile 43 | cProfile.run("heap_sort(random_list.copy(), False)") 44 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/CSVDataSource.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | public class CSVDataSource implements IDataSource { 6 | 7 | @Override 8 | public void saveData(List data, String path) { 9 | try (PrintWriter writer = new PrintWriter(new FileWriter(path))) { 10 | for (String[] row : data) { 11 | StringBuilder rowBuilder = new StringBuilder(); 12 | for (int i = 0; i < row.length; i++) { 13 | rowBuilder.append(row[i]); 14 | if (i < row.length - 1) { 15 | rowBuilder.append(","); 16 | } 17 | } 18 | writer.println(rowBuilder.toString()); 19 | } 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | @Override 26 | public List loadData(String path) { 27 | List data = new ArrayList<>(); 28 | try (BufferedReader reader = new BufferedReader(new FileReader(path))) { 29 | String line; 30 | while ((line = reader.readLine()) != null) { 31 | String[] values = line.split(","); 32 | data.add(values); 33 | } 34 | } catch (IOException e) { 35 | e.printStackTrace(); 36 | } 37 | return data; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /HDT 8 Heap/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | import java.util.Comparator; 5 | 6 | public class Main { 7 | public static void main(String[] args) { 8 | // Crear el comparador de prioridades 9 | Comparator comparator = new ComparadorNumeros<>(); 10 | 11 | // Crear el heap utilizando el árbol binario iterativo 12 | HeapUsingIterativeBinaryTree heap = new HeapUsingIterativeBinaryTree<>(comparator); 13 | 14 | // Leer los procesos del archivo y agregarlos al heap 15 | try { 16 | BufferedReader reader = new BufferedReader(new FileReader("procesos.txt")); 17 | String line; 18 | while ((line = reader.readLine()) != null) { 19 | String[] parts = line.split(","); 20 | String nombre = parts[0]; 21 | String usuario = parts[1]; 22 | int nice = Integer.parseInt(parts[2]); 23 | int priority = 20 + nice; 24 | Proceso proceso = new Proceso(nombre, usuario, nice, priority); 25 | heap.Insert(priority, proceso); 26 | } 27 | reader.close(); 28 | } catch (IOException e) { 29 | e.printStackTrace(); 30 | } 31 | 32 | // Procesar los procesos del heap 33 | while (!heap.isEmpty()) { 34 | Proceso proceso = heap.remove(); 35 | System.out.println(proceso); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /HDT 8 Heap/src/HeapUsingIterativeBinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | import static org.junit.Assert.*; 3 | import java.util.Comparator; 4 | 5 | public class HeapUsingIterativeBinaryTreeTest { 6 | 7 | @Test 8 | public void testInsertAndRemove() { 9 | // Crear un comparador de prioridades 10 | Comparator comparator = new ComparadorNumeros<>(); 11 | 12 | // Crear un heap utilizando el árbol binario iterativo 13 | HeapUsingIterativeBinaryTree heap = new HeapUsingIterativeBinaryTree<>(comparator); 14 | 15 | // Prueba Insert y remove con elementos 16 | heap.Insert(10, "A"); 17 | heap.Insert(20, "B"); 18 | heap.Insert(15, "C"); 19 | 20 | assertEquals(3, heap.count()); 21 | 22 | assertEquals("A", heap.remove()); 23 | assertEquals(2, heap.count()); 24 | 25 | assertEquals("C", heap.remove()); 26 | assertEquals(1, heap.count()); 27 | 28 | assertEquals("B", heap.remove()); 29 | assertEquals(0, heap.count()); 30 | } 31 | 32 | @Test 33 | public void testInsertAndRemoveWithEmptyHeap() { 34 | // Crear un comparador de prioridades 35 | Comparator comparator = new ComparadorNumeros<>(); 36 | 37 | // Crear un heap utilizando el árbol binario iterativo 38 | HeapUsingIterativeBinaryTree heap = new HeapUsingIterativeBinaryTree<>(comparator); 39 | 40 | // Prueba remove en un heap vacío 41 | assertNull(heap.remove()); 42 | } 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /HDT8 Priority Queue JCF/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | import java.util.Comparator; 5 | import java.util.PriorityQueue; 6 | 7 | public class Main { 8 | public static void main(String[] args) { 9 | // Crear el comparador de prioridades 10 | Comparator comparator = Comparator.comparingInt(Proceso::getPriority); 11 | 12 | // Crear el PriorityQueue utilizando el comparador de prioridades 13 | PriorityQueue priorityQueue = new PriorityQueue<>(comparator); 14 | 15 | // Leer los procesos del archivo y agregarlos al PriorityQueue 16 | try { 17 | BufferedReader reader = new BufferedReader(new FileReader("procesos.txt")); 18 | String line; 19 | while ((line = reader.readLine()) != null) { 20 | String[] parts = line.split(","); 21 | String nombre = parts[0]; 22 | String usuario = parts[1]; 23 | int nice = Integer.parseInt(parts[2]); 24 | int priority = 20 + nice; 25 | Proceso proceso = new Proceso(nombre, usuario, nice, priority); 26 | priorityQueue.add(proceso); 27 | } 28 | reader.close(); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | 33 | // Procesar los procesos del PriorityQueue 34 | while (!priorityQueue.isEmpty()) { 35 | Proceso proceso = priorityQueue.poll(); 36 | System.out.println(proceso); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/Student.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Student extends User { 5 | private List enrolledCourses; 6 | private List grades; 7 | private List paymentHistory; 8 | 9 | // Constructor predeterminado requerido por Jackson 10 | public Student() { 11 | super("", ""); // Llama al constructor de la clase base con valores predeterminados o vacíos 12 | this.enrolledCourses = new ArrayList<>(); 13 | this.grades = new ArrayList<>(); 14 | this.paymentHistory = new ArrayList<>(); 15 | } 16 | 17 | public Student(String username, String password) { 18 | super(username, password); 19 | this.enrolledCourses = new ArrayList<>(); 20 | this.grades = new ArrayList<>(); 21 | this.paymentHistory = new ArrayList<>(); 22 | } 23 | 24 | public void enrollCourse(Course course) { 25 | enrolledCourses.add(course); 26 | course.addStudent(this); 27 | } 28 | 29 | public double getGradeForClass(String className) { 30 | int index = enrolledCourses.indexOf(className); 31 | if (index != -1) { 32 | return grades.get(index); 33 | } else { 34 | return -1; 35 | } 36 | } 37 | 38 | public boolean makePayment(double amount) { 39 | // Logic to make payment 40 | // Assuming the payment is successful 41 | paymentHistory.add(amount); 42 | return true; 43 | } 44 | 45 | public List viewPaymentHistory() { 46 | return paymentHistory; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/TXTDataSource.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.util.List; 9 | 10 | public class TXTDataSource implements IDataSource { 11 | 12 | @Override 13 | public void saveData(List data, String path) { 14 | try (FileWriter writer = new FileWriter(path)) { 15 | for (String[] record : data) { 16 | for (String field : record) { 17 | writer.write(field + ","); 18 | } 19 | writer.write("\n"); 20 | } 21 | System.out.println("Datos guardados correctamente en el archivo: " + path); 22 | } catch (IOException e) { 23 | e.printStackTrace(); 24 | System.out.println("Error al guardar los datos en el archivo: " + path); 25 | } 26 | } 27 | 28 | @Override 29 | public List loadData(String path) { 30 | List loadedData = new ArrayList<>(); 31 | try (BufferedReader reader = new BufferedReader(new FileReader(path))) { 32 | String line; 33 | while ((line = reader.readLine()) != null) { 34 | String[] fields = line.split(","); 35 | loadedData.add(fields); 36 | } 37 | System.out.println("Datos cargados correctamente desde el archivo: " + path); 38 | } catch (IOException e) { 39 | e.printStackTrace(); 40 | System.out.println("Error al cargar los datos desde el archivo: " + path); 41 | } 42 | return loadedData; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Diccionario Idiomas/src/BinarySearchTreeTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | import org.junit.Test; 3 | import java.util.Comparator; 4 | 5 | public class BinarySearchTreeTest { 6 | 7 | @Test 8 | public void testInsertAndFind() { 9 | BinarySearchTree tree = new BinarySearchTree<>(Comparator.naturalOrder()); 10 | tree.insert(5, "Five"); 11 | tree.insert(3, "Three"); 12 | tree.insert(7, "Seven"); 13 | tree.insert(1, "One"); 14 | 15 | assertEquals("Five", tree.find(5)); 16 | assertEquals("Three", tree.find(3)); 17 | assertEquals("Seven", tree.find(7)); 18 | assertEquals("One", tree.find(1)); 19 | assertNull(tree.find(10)); 20 | } 21 | 22 | @Test 23 | public void testInOrderTraversal() { 24 | BinarySearchTree tree = new BinarySearchTree<>(Comparator.naturalOrder()); 25 | tree.insert(5, "Five"); 26 | tree.insert(3, "Three"); 27 | tree.insert(7, "Seven"); 28 | tree.insert(1, "One"); 29 | 30 | SaveInArrayListWalk walk = new SaveInArrayListWalk<>(); 31 | tree.InOrderWalk(walk); 32 | assertEquals("[One, Three, Five, Seven]", walk.getListado().toString()); 33 | } 34 | 35 | @Test 36 | public void testRemove() { 37 | BinarySearchTree tree = new BinarySearchTree<>(Comparator.naturalOrder()); 38 | tree.insert(5, "Five"); 39 | tree.insert(3, "Three"); 40 | tree.insert(7, "Seven"); 41 | tree.insert(1, "One"); 42 | 43 | assertEquals("Five", tree.remove(5)); 44 | assertNull(tree.find(5)); 45 | 46 | assertEquals("One", tree.remove(1)); 47 | assertNull(tree.find(1)); 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/Admin.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Admin extends User { 5 | private List courses; 6 | private List students; 7 | private List faculties; 8 | 9 | // Constructor predeterminado sin argumentos 10 | public Admin() { 11 | super("", ""); // Puedes proporcionar valores predeterminados para el nombre de usuario y la contraseña si es necesario 12 | courses = new ArrayList<>(); 13 | students = new ArrayList<>(); 14 | faculties = new ArrayList<>(); 15 | } 16 | 17 | public Admin(String username, String password) { 18 | super(username, password); 19 | courses = new ArrayList<>(); 20 | students = new ArrayList<>(); 21 | faculties = new ArrayList<>(); 22 | } 23 | 24 | public void createCourse(String courseName, Faculty faculty) { 25 | Course course = new Course(courseName, faculty); 26 | courses.add(course); 27 | } 28 | 29 | public void createStudent(String username, String password) { 30 | Student student = new Student(username, password); 31 | students.add(student); 32 | } 33 | 34 | public void createFaculty(String username, String password) { 35 | Faculty faculty = new Faculty(username, password); 36 | faculties.add(faculty); 37 | } 38 | 39 | public void assignStudentToCourse(Student student, Course course) { 40 | course.addStudent(student); 41 | } 42 | 43 | public void assignFacultyToCourse(Faculty faculty, Course course) { 44 | course.setCourseFaculty(faculty); 45 | } 46 | 47 | public void assignPaymentToFaculty(Faculty faculty, double amount) { 48 | // Implement logic to assign payment to faculty 49 | } 50 | 51 | public void generateGradeReport(Student student) { 52 | // Implement logic to generate a grade report for a student 53 | } 54 | 55 | public void generatePaymentReport(Student student) { 56 | // Implement logic to generate a payment report for a student 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/ControladorTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | import java.util.ArrayList; 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.assertNotNull; 5 | import static org.junit.Assert.fail; 6 | 7 | public class ControladorTest { 8 | 9 | @Test 10 | public void testAdd() { 11 | Controlador controlador = new Controlador(); 12 | int result = controlador.add(2, 3); 13 | assertEquals(5, result); 14 | } 15 | 16 | @Test 17 | public void testSubstraction() { 18 | Controlador controlador = new Controlador(); 19 | int result = controlador.substraction(5, 3); 20 | assertEquals(2, result); 21 | } 22 | 23 | @Test 24 | public void testMultiplication() { 25 | Controlador controlador = new Controlador(); 26 | int result = controlador.multiplication(2, 3); 27 | assertEquals(6, result); 28 | } 29 | 30 | @Test 31 | public void testDivision() throws Exception { 32 | Controlador controlador = new Controlador(); 33 | int result = controlador.division(6, 3); 34 | assertEquals(2, result); 35 | } 36 | 37 | @Test(expected = Exception.class) 38 | public void testDivisionByZero() throws Exception { 39 | Controlador controlador = new Controlador(); 40 | controlador.division(5, 0); 41 | } 42 | 43 | @Test 44 | public void testResidue() throws Exception { 45 | Controlador controlador = new Controlador(); 46 | int result = controlador.residue(7, 3); 47 | assertEquals(0, result); 48 | } 49 | 50 | @Test 51 | public void testRead() throws Exception { 52 | Controlador controlador = new Controlador(); 53 | 54 | try { 55 | ArrayList result = controlador.read("12345"); 56 | 57 | // Verificar que el resultado no sea null 58 | 59 | 60 | // Resto del código de verificación 61 | } catch (Exception e) { 62 | fail("Excepción inesperada: " + e.getMessage()); 63 | } 64 | } 65 | @Test 66 | public void testSolve() throws Exception { 67 | Controlador controlador = new Controlador(); 68 | ArrayList elements = new ArrayList<>(); 69 | elements.add('1'); 70 | elements.add('2'); 71 | elements.add('+'); 72 | elements.add('4'); 73 | elements.add('*'); 74 | elements.add('3'); 75 | elements.add('+'); 76 | 77 | int result = controlador.solve(elements); 78 | assertEquals(0, result); 79 | } 80 | 81 | // Add more tests for other methods or edge cases if needed 82 | } 83 | -------------------------------------------------------------------------------- /Sorts/MergeSort.py: -------------------------------------------------------------------------------- 1 | import cProfile 2 | import random 3 | import unittest 4 | 5 | def merge_sort(arr, reverse=False): 6 | if len(arr) <= 1: 7 | return arr 8 | else: 9 | mid = len(arr) // 2 10 | left_half = arr[:mid] 11 | right_half = arr[mid:] 12 | 13 | left_half = merge_sort(left_half, reverse) 14 | right_half = merge_sort(right_half, reverse) 15 | 16 | return merge(left_half, right_half, reverse) 17 | 18 | def merge(left, right, reverse): 19 | result = [] 20 | left_idx, right_idx = 0, 0 21 | 22 | if reverse: 23 | while left_idx < len(left) and right_idx < len(right): 24 | if left[left_idx] > right[right_idx]: 25 | result.append(left[left_idx]) 26 | left_idx += 1 27 | else: 28 | result.append(right[right_idx]) 29 | right_idx += 1 30 | else: 31 | while left_idx < len(left) and right_idx < len(right): 32 | if left[left_idx] < right[right_idx]: 33 | result.append(left[left_idx]) 34 | left_idx += 1 35 | else: 36 | result.append(right[right_idx]) 37 | right_idx += 1 38 | 39 | result.extend(left[left_idx:]) 40 | result.extend(right[right_idx:]) 41 | return result 42 | 43 | class TestMergeSort(unittest.TestCase): 44 | def test_merge_sort_ascending(self): 45 | arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] 46 | expected = [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] 47 | self.assertEqual(merge_sort(arr), expected) 48 | 49 | def test_merge_sort_descending(self): 50 | arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] 51 | expected = [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1] 52 | self.assertEqual(merge_sort(arr, reverse=True), expected) 53 | 54 | if __name__ == "__main__": 55 | # Generar una lista de números aleatorios 56 | random.seed(42) # Fijar la semilla para obtener los mismos resultados cada vez 57 | lista = [random.randint(0, 10000) for _ in range(10000)] 58 | 59 | # Mostrar la lista desordenada 60 | print("Lista desordenada:") 61 | print(lista) 62 | 63 | # Medir el tiempo de ejecución del algoritmo 64 | profiler = cProfile.Profile() 65 | profiler.enable() 66 | 67 | # Ordenar la lista utilizando Merge Sort 68 | sorted_list = merge_sort(lista) 69 | 70 | profiler.disable() 71 | 72 | # Mostrar la lista ordenada 73 | print("\nLista ordenada de forma ascendente:") 74 | print(sorted_list) 75 | 76 | # Pruebas unitarias 77 | unittest.main(argv=[''], exit=False) 78 | 79 | profiler.print_stats(sort='cumtime') 80 | -------------------------------------------------------------------------------- /CalculadoraPostfix/src/Calculadora.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileNotFoundException; 3 | import java.io.FileReader; 4 | import java.io.IOException; 5 | import java.util. Vector; 6 | 7 | public class Calculadora { 8 | public static void main(String[] args) { 9 | Controlador controlador = new Controlador(); 10 | StackWithVector vectores = new StackWithVector(); 11 | 12 | String filePath = "C:\\Users\\Usuario\\Downloads\\a.txt"; // Reemplaza con la ruta de tu archivo .txt 13 | 14 | try { 15 | FileReader fileReader = new FileReader(filePath); 16 | BufferedReader bufferedReader = new BufferedReader(fileReader); 17 | 18 | String line; 19 | while ((line = bufferedReader.readLine()) != null) { 20 | String[] tokens = line.split("\\s+"); 21 | 22 | for (String token : tokens) { 23 | if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) { 24 | if (vectores.count() >= 2) { 25 | int n1 = Integer.parseInt(vectores.pop()); 26 | int n2 = Integer.parseInt(vectores.pop()); 27 | 28 | switch (token) { 29 | case "+": 30 | vectores.push(String.valueOf(controlador.add(n2, n1))); 31 | break; 32 | case "-": 33 | vectores.push(String.valueOf(controlador.substraction(n2, n1))); 34 | break; 35 | case "*": 36 | vectores.push(String.valueOf(controlador.multiplication(n2, n1))); 37 | break; 38 | case "/": 39 | vectores.push(String.valueOf(controlador.division(n2, n1))); 40 | break; 41 | default: 42 | throw new RuntimeException("Operador no reconocido: " + token); 43 | } 44 | } else { 45 | // Manejar el caso de no tener suficientes operandos en la pila 46 | throw new RuntimeException("No hay suficientes operandos para realizar la operación."); 47 | } 48 | } else { 49 | vectores.push(token); 50 | } 51 | } 52 | } 53 | 54 | } catch (FileNotFoundException e) { 55 | throw new RuntimeException(e); 56 | } catch (IOException e) { 57 | throw new RuntimeException(e); 58 | } catch (Exception e) { 59 | throw new RuntimeException(e); 60 | } 61 | 62 | // Imprimir resultado final que queda en la última posición de la pila 63 | System.out.println(vectores.peek()); 64 | } 65 | } 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /Diccionario Idiomas/src/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | public class BinarySearchTree implements ITree { 4 | 5 | private int count; 6 | private TreeNode root; 7 | private Comparator keyComparator; 8 | 9 | public BinarySearchTree(Comparator keyComparator) { 10 | this.root = null; 11 | this.count = 0; 12 | this.keyComparator = keyComparator; 13 | } 14 | 15 | @Override 16 | public void insert(K key, V value) { 17 | TreeNode newNode = new TreeNode<>(key, value); 18 | if (isEmpty()) { // Insert in the root 19 | this.root = newNode; 20 | this.count++; 21 | } else { // Insert in a leaf 22 | internalInsert(this.root, newNode); 23 | } 24 | } 25 | 26 | private void internalInsert(TreeNode parent, TreeNode node) { 27 | if (parent != null) { 28 | int result = this.keyComparator.compare(node.getKey(), parent.getKey()); 29 | if (result > 0) { 30 | if (parent.getRight() == null) { 31 | parent.setRight(node); 32 | node.setParent(parent); 33 | this.count++; 34 | } else { 35 | internalInsert(parent.getRight(), node); 36 | } 37 | } else if (result < 0) { 38 | if (parent.getLeft() == null) { 39 | parent.setLeft(node); 40 | node.setParent(parent); 41 | this.count++; 42 | } else { 43 | internalInsert(parent.getLeft(), node); 44 | } 45 | } 46 | } 47 | } 48 | 49 | @Override 50 | public V find(K keyToFind) { 51 | if (!isEmpty()) { 52 | return internalSearch(root, keyToFind); 53 | } else { 54 | return null; 55 | } 56 | } 57 | 58 | private V internalSearch(TreeNode actualNode, K keyToFind) { 59 | if (actualNode != null) { 60 | int result = this.keyComparator.compare(keyToFind, actualNode.getKey()); 61 | if (result == 0) { 62 | return actualNode.getValue(); 63 | } else if (result > 0) { 64 | return internalSearch(actualNode.getRight(), keyToFind); 65 | } else if (result < 0) { 66 | return internalSearch(actualNode.getLeft(), keyToFind); 67 | } 68 | } 69 | return null; 70 | } 71 | 72 | @Override 73 | public int count() { 74 | return count; 75 | } 76 | 77 | @Override 78 | public boolean isEmpty() { 79 | return count == 0; 80 | } 81 | 82 | @Override 83 | public V remove(K key) { 84 | if (!isEmpty()) { 85 | // Implementación de eliminación aquí 86 | } 87 | return null; 88 | } 89 | 90 | @Override 91 | public void InOrderWalk(IWalk walk) { 92 | InternalInOrderWalk(root, walk); 93 | } 94 | 95 | private void InternalInOrderWalk(TreeNode actualNode, IWalk walk) { 96 | if (actualNode != null) { 97 | InternalInOrderWalk(actualNode.getLeft(), walk); 98 | walk.doWalk(actualNode.getValue()); 99 | InternalInOrderWalk(actualNode.getRight(), walk); 100 | } 101 | } 102 | 103 | @Override 104 | public void PreOrderWalk(IWalk walk) { 105 | InternalPreOrderWalk(root, walk); 106 | } 107 | 108 | private void InternalPreOrderWalk(TreeNode actualNode, IWalk walk) { 109 | if (actualNode != null) { 110 | walk.doWalk(actualNode.getValue()); 111 | InternalPreOrderWalk(actualNode.getLeft(), walk); 112 | InternalPreOrderWalk(actualNode.getRight(), walk); 113 | } 114 | } 115 | 116 | @Override 117 | public void PostOrderWalk(IWalk walk) { 118 | InternalPostOrderWalk(root, walk); 119 | } 120 | 121 | private void InternalPostOrderWalk(TreeNode actualNode, IWalk walk) { 122 | if (actualNode != null) { 123 | InternalPostOrderWalk(actualNode.getLeft(), walk); 124 | InternalPostOrderWalk(actualNode.getRight(), walk); 125 | walk.doWalk(actualNode.getValue()); 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /Hoja de Trabajo 5/HDT5.py: -------------------------------------------------------------------------------- 1 | import simpy 2 | import random 3 | import statistics 4 | import matplotlib.pyplot as plt 5 | 6 | # Semilla para reproducibilidad 7 | RANDOM_SEED = 42 8 | random.seed(RANDOM_SEED) 9 | 10 | # Parámetros de la simulación 11 | INTERVALO = 10 # Intervalo de llegada de procesos (en unidades de tiempo) 12 | MEMORIA_RAM = 100 # Memoria RAM disponible 13 | VELOCIDAD_CPU = 3 # Instrucciones que puede ejecutar el CPU en una unidad de tiempo 14 | 15 | # Variables para almacenar resultados 16 | resultados = [] 17 | 18 | class SistemaOperativo: 19 | def __init__(self, env, memoria, cpu): 20 | self.env = env 21 | self.memoria = memoria 22 | self.cpu = cpu 23 | 24 | def run(self, num_procesos): 25 | for i in range(num_procesos): 26 | yield self.env.process(self.proceso(i)) 27 | 28 | def proceso(self, id_proceso): 29 | memoria_requerida = random.randint(1, 10) 30 | yield self.memoria.get(memoria_requerida) 31 | 32 | tiempo_inicio = self.env.now # Capturamos el tiempo de inicio 33 | instrucciones_totales = random.randint(1, 10) 34 | while instrucciones_totales > 0: 35 | with self.cpu.request() as req: 36 | yield req 37 | yield self.env.timeout(1 / VELOCIDAD_CPU) 38 | instrucciones_totales -= min(VELOCIDAD_CPU, instrucciones_totales) 39 | if instrucciones_totales == 0: 40 | break 41 | elif random.randint(1, 21) == 1: 42 | yield self.env.timeout(random.randint(1, 2)) 43 | # Calculamos el tiempo de ejecución y lo agregamos a la lista 44 | tiempo_fin = self.env.now 45 | tiempo_ejecucion = tiempo_fin - tiempo_inicio 46 | resultados.append(tiempo_ejecucion) 47 | 48 | 49 | def ejecutar_simulacion(num_procesos, intervalo_llegada): 50 | env = simpy.Environment() 51 | memoria = simpy.Container(env, init=MEMORIA_RAM, capacity=MEMORIA_RAM) 52 | cpu = simpy.Resource(env, capacity=1) 53 | sistema = SistemaOperativo(env, memoria, cpu) 54 | env.process(sistema.run(num_procesos)) 55 | env.run(until=intervalo_llegada * num_procesos) 56 | 57 | def calcular_promedio_y_desviacion(resultados): 58 | promedio = statistics.mean(resultados) 59 | desviacion = statistics.stdev(resultados) 60 | return promedio, desviacion 61 | 62 | def generar_grafica(datos): 63 | plt.plot(datos.keys(), datos.values(), marker='o') 64 | plt.xlabel('Número de procesos') 65 | plt.ylabel('Tiempo promedio') 66 | plt.title('Tiempo promedio vs. Número de procesos') 67 | plt.grid(True) 68 | plt.show() 69 | 70 | # a. Ejecutar simulación con diferentes cantidades de procesos (25, 50, 100, 150, 200) y calcular promedio y desviación 71 | cantidades_procesos = [25, 50, 100, 150, 200] 72 | resultados_a = {} 73 | for cantidad in cantidades_procesos: 74 | resultados.clear() 75 | ejecutar_simulacion(cantidad, INTERVALO) 76 | promedio, desviacion = calcular_promedio_y_desviacion(resultados) 77 | resultados_a[cantidad] = promedio 78 | print("Resultados (a):", resultados_a) 79 | generar_grafica(resultados_a) 80 | 81 | # b. Volver a correr simulación con intervalos de llegada más rápidos (5, 1) 82 | intervalos_llegada = [5, 1] 83 | resultados_b = {} 84 | for intervalo in intervalos_llegada: 85 | resultados.clear() 86 | ejecutar_simulacion(cantidades_procesos[-1], intervalo) 87 | promedio, desviacion = calcular_promedio_y_desviacion(resultados) 88 | resultados_b[intervalo] = promedio 89 | print("Resultados (b):", resultados_b) 90 | generar_grafica(resultados_b) 91 | 92 | # c. Pruebas para reducir el tiempo promedio 93 | # i. Incrementar la memoria a 200 94 | resultados_c_i = {} 95 | MEMORIA_RAM = 200 96 | for cantidad in cantidades_procesos: 97 | resultados.clear() 98 | ejecutar_simulacion(cantidad, INTERVALO) 99 | promedio, desviacion = calcular_promedio_y_desviacion(resultados) 100 | resultados_c_i[cantidad] = promedio 101 | print("Resultados (c-i):", resultados_c_i) 102 | generar_grafica(resultados_c_i) 103 | 104 | # ii. Procesador más rápido (6 instrucciones por unidad de tiempo) 105 | resultados_c_ii = {} 106 | VELOCIDAD_CPU = 6 107 | for cantidad in cantidades_procesos: 108 | resultados.clear() 109 | ejecutar_simulacion(cantidad, INTERVALO) 110 | promedio, desviacion = calcular_promedio_y_desviacion(resultados) 111 | resultados_c_ii[cantidad] = promedio 112 | print("Resultados (c-ii):", resultados_c_ii) 113 | generar_grafica(resultados_c_ii) 114 | 115 | # iii. Emplear 2 procesadores 116 | resultados_c_iii = {} 117 | VELOCIDAD_CPU = 3 # Restaurar la velocidad del CPU 118 | for cantidad in cantidades_procesos: 119 | env = simpy.Environment() # Definir un nuevo entorno para cada ejecución 120 | cpu = simpy.Resource(env, capacity=2) # Crear dos recursos de CPU 121 | memoria = simpy.Container(env, init=MEMORIA_RAM, capacity=MEMORIA_RAM) 122 | sistema = SistemaOperativo(env, memoria, cpu) 123 | env.process(sistema.run(cantidad)) 124 | env.run(until=INTERVALO * cantidad) # Ejecutar la simulación 125 | promedio, desviacion = calcular_promedio_y_desviacion(resultados) 126 | resultados_c_iii[cantidad] = promedio 127 | print("Resultados (c-iii):", resultados_c_iii) 128 | generar_grafica(resultados_c_iii) -------------------------------------------------------------------------------- /Diccionario Idiomas/src/DictionaryProgram.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | 6 | public class DictionaryProgram { 7 | 8 | public static void main(String[] args) { 9 | // Crear árboles binarios de búsqueda para cada idioma 10 | BinarySearchTree englishTree = new BinarySearchTree<>(String.CASE_INSENSITIVE_ORDER); 11 | BinarySearchTree spanishTree = new BinarySearchTree<>(String.CASE_INSENSITIVE_ORDER); 12 | BinarySearchTree frenchTree = new BinarySearchTree<>(String.CASE_INSENSITIVE_ORDER); 13 | 14 | // Leer el archivo de diccionario y construir los árboles 15 | buildDictionaryTrees("diccionario.txt", englishTree, spanishTree, frenchTree); 16 | // Leer el archivo de texto y traducir las palabras 17 | translateText("texto.txt", englishTree, spanishTree, frenchTree); 18 | 19 | // Recorrer el árbol de inglés In-order y mostrar las palabras ordenadas 20 | System.out.println("Palabras ordenadas en inglés:"); 21 | inOrderTraversal(englishTree); 22 | 23 | // Recorrer el árbol de español In-order y mostrar las palabras ordenadas 24 | System.out.println("\nPalabras ordenadas en español:"); 25 | inOrderTraversalesp(spanishTree); 26 | 27 | // Recorrer el árbol de francés In-order y mostrar las palabras ordenadas 28 | System.out.println("\nPalabras ordenadas en francés:"); 29 | inOrderTraversalfre(frenchTree); 30 | 31 | // Leer el archivo de texto y traducir las palabras 32 | System.out.println("Frase traducida"); 33 | translateText("texto.txt", englishTree, spanishTree, frenchTree); 34 | } 35 | 36 | // Método para construir los árboles del diccionario a partir de un archivo 37 | private static void buildDictionaryTrees(String fileName, 38 | BinarySearchTree englishTree, 39 | BinarySearchTree spanishTree, 40 | BinarySearchTree frenchTree) { 41 | try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { 42 | String line; 43 | while ((line = br.readLine()) != null) { 44 | String[] parts = line.split(","); 45 | if (parts.length == 3) { 46 | Association association = new Association(parts[0], parts[1], parts[2]); 47 | englishTree.insert(parts[0], association); 48 | spanishTree.insert(parts[1], association); 49 | frenchTree.insert(parts[2], association); 50 | } 51 | } 52 | } catch (IOException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | private static void inOrderTraversalesp(BinarySearchTree tree) { 57 | ArrayList words = new ArrayList<>(); 58 | tree.InOrderWalk((Association association) -> { 59 | words.add(association.getSpanish() + " (" + association.getEnglish() + ", " + association.getFrench() + ")"); 60 | }); 61 | for (String word : words) { 62 | System.out.println(word); 63 | } 64 | } 65 | private static void inOrderTraversal(BinarySearchTree tree) { 66 | ArrayList words = new ArrayList<>(); 67 | tree.InOrderWalk((Association association) -> { 68 | words.add(association.getEnglish() + " (" + association.getSpanish() + ", " + association.getFrench() + ")"); 69 | }); 70 | for (String word : words) { 71 | System.out.println(word); 72 | } 73 | } 74 | private static void inOrderTraversalfre(BinarySearchTree tree) { 75 | ArrayList words = new ArrayList<>(); 76 | tree.InOrderWalk((Association association) -> { 77 | words.add(association.getFrench() + " (" + association.getSpanish() + ", " + association.getEnglish() + ")"); 78 | }); 79 | for (String word : words) { 80 | System.out.println(word); 81 | } 82 | } 83 | 84 | // Método para traducir el texto del archivo de entrada 85 | private static void translateText(String fileName, 86 | BinarySearchTree englishTree, 87 | BinarySearchTree spanishTree, 88 | BinarySearchTree frenchTree) { 89 | try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { 90 | String line; 91 | while ((line = br.readLine()) != null) { 92 | String[] words = line.split("\\s+"); 93 | for (String word : words) { 94 | translateWord(word, englishTree, spanishTree, frenchTree); 95 | } 96 | System.out.println(); 97 | } 98 | } catch (IOException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | // Método para traducir una palabra y mostrar el resultado 104 | private static void translateWord(String word, 105 | BinarySearchTree englishTree, 106 | BinarySearchTree spanishTree, 107 | BinarySearchTree frenchTree) { 108 | Association association = englishTree.find(word); 109 | if (association != null) { 110 | System.out.print(association.getSpanish() + " "); 111 | } else { 112 | association = spanishTree.find(word); 113 | if (association != null) { 114 | System.out.print(association.getEnglish() + " "); 115 | } else { 116 | association = frenchTree.find(word); 117 | if (association != null) { 118 | System.out.print(association.getEnglish() + " "); 119 | } else { 120 | System.out.print("*" + word + "* "); 121 | } 122 | } 123 | } 124 | } 125 | } -------------------------------------------------------------------------------- /HDT 8 Heap/src/HeapUsingIterativeBinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Comparator; 3 | 4 | public class HeapUsingIterativeBinaryTree implements IHeap { 5 | 6 | private int _count; 7 | private TreeNode _root; 8 | private Comparator

_priorityComparator; 9 | 10 | public HeapUsingIterativeBinaryTree(Comparator

priorityComparator) { 11 | _count = 0; 12 | _priorityComparator = priorityComparator; 13 | } 14 | 15 | @Override 16 | public void Insert(P priority, V value) { 17 | TreeNode newNode = new TreeNode(priority, value); 18 | 19 | if (count() == 0) { //Inserto en la raiz 20 | _count++; 21 | _root = newNode; 22 | } else { 23 | 24 | _count++; 25 | 26 | byte[] movimientos = convertToBinary(_count); 27 | 28 | //Reccorer de acuerdo a los movimientos 29 | int index = 1; 30 | TreeNode actual = _root; 31 | 32 | while (index < movimientos.length) { 33 | 34 | if (index == movimientos.length - 1) { 35 | if (movimientos[index] == 0) { // Inserto en el hijo izquierdo 36 | actual.set_left(newNode); 37 | } else { //Inserto en el hijo derecho 38 | actual.set_right(newNode); 39 | } 40 | newNode.set_parent(actual); 41 | } else { 42 | if (movimientos[index] == 0) { // Inserto en el hijo izquierdo 43 | actual = actual.get_left(); 44 | } else { //Inserto en el hijo derecho 45 | actual = actual.get_right(); 46 | } 47 | } 48 | 49 | index++; 50 | } 51 | 52 | 53 | //Hacer Swap 54 | actual = newNode; 55 | while((actual != null) && (actual.get_parent() != null)) { 56 | Swap(actual); 57 | actual = actual.get_parent(); 58 | } 59 | 60 | } 61 | 62 | } 63 | 64 | private byte[] convertToBinary(int value) { 65 | 66 | ArrayList listBytes = new ArrayList(); 67 | 68 | while (value > 0) { 69 | listBytes.add( (byte)(value % 2) ); 70 | value = value / 2; 71 | } 72 | //listBytes.add((byte) (value % 2) ); 73 | 74 | byte[] binaryBytes = new byte[listBytes.size()]; 75 | 76 | for (int i = listBytes.size() - 1; i >= 0; i-- ) { 77 | binaryBytes[listBytes.size() - 1 - i] = listBytes.get(i); 78 | } 79 | 80 | return binaryBytes; 81 | } 82 | 83 | private void Swap(TreeNode actualNode) { 84 | if (actualNode != null) { 85 | 86 | if (actualNode.get_parent() != null) { //is not the root 87 | 88 | int result = _priorityComparator.compare(actualNode.get_priority(), actualNode.get_parent().get_priority()); 89 | 90 | if (result > 0) { //if child is greater than parent 91 | P tempP = actualNode.get_priority(); 92 | V tempV = actualNode.get_value(); 93 | 94 | actualNode.set_priority(actualNode.get_parent().get_priority()); 95 | actualNode.set_value(actualNode.get_parent().get_value()); 96 | 97 | actualNode.get_parent().set_priority(tempP); 98 | actualNode.get_parent().set_value(tempV); 99 | } 100 | 101 | } 102 | 103 | } 104 | } 105 | 106 | 107 | @Override 108 | public V get() { 109 | if (isEmpty()) 110 | return null; 111 | else 112 | return _root.get_value(); 113 | } 114 | 115 | @Override 116 | public V remove() { 117 | 118 | if (isEmpty()) { 119 | return null; 120 | } 121 | 122 | if (count() == 1) { 123 | _count--; 124 | TreeNode temporal = _root; 125 | _root = null; 126 | return temporal.get_value(); 127 | } 128 | 129 | //if has more than 1 element 130 | 131 | // Obtener el binario de la cantidad de nodos 132 | byte[] movimientos = convertToBinary(_count); 133 | 134 | // Encontrar el nodo a eliminar 135 | //Reccorer de acuerdo a los movimientos 136 | int index = 1; 137 | TreeNode actual = _root; 138 | TreeNode nodoToBeDeleted = null; 139 | 140 | while (index < movimientos.length) { 141 | 142 | if (index == movimientos.length - 1) { 143 | if (movimientos[index] == 0) { // Inserto en el hijo izquierdo 144 | nodoToBeDeleted = actual.get_left(); 145 | } else { //Inserto en el hijo derecho 146 | nodoToBeDeleted = actual.get_right(); 147 | } 148 | 149 | } else { 150 | if (movimientos[index] == 0) { // Inserto en el hijo izquierdo 151 | actual = actual.get_left(); 152 | } else { //Inserto en el hijo derecho 153 | actual = actual.get_right(); 154 | } 155 | } 156 | 157 | index++; 158 | } 159 | 160 | // Hacer Swap de la hoja con la raiz 161 | P tempPriority = nodoToBeDeleted.get_priority(); 162 | V tempValue = nodoToBeDeleted.get_value(); 163 | 164 | nodoToBeDeleted.set_priority(_root.get_priority()); 165 | nodoToBeDeleted.set_value(_root.get_value()); 166 | 167 | _root.set_priority(tempPriority); 168 | _root.set_value(tempValue); 169 | 170 | 171 | // Eliminar el nodo hoja 172 | tempPriority = nodoToBeDeleted.get_priority(); 173 | tempValue = nodoToBeDeleted.get_value(); 174 | 175 | TreeNode parent = nodoToBeDeleted.get_parent(); 176 | if (parent.get_left() == nodoToBeDeleted) 177 | parent.set_left(null); 178 | else 179 | parent.set_right(null); 180 | 181 | 182 | // buscar el lugar de insercion 183 | actual = _root; 184 | 185 | while (actual != null) { 186 | 187 | boolean actualHasLeftChild = actual.get_left() != null; 188 | boolean actualHasRightChild = actual.get_right() != null; 189 | 190 | if (actualHasLeftChild && actualHasRightChild) { //Tiene a los 2 hijos 191 | 192 | //Si tiene a los dos hijos verifico quien es el mayor 193 | int result = _priorityComparator.compare(actual.get_left().get_priority(), actual.get_right().get_priority()); 194 | 195 | if (result == 0) { //Son iguales 196 | 197 | result = _priorityComparator.compare(actual.get_priority(), actual.get_left().get_priority()); 198 | if (result < 0) { 199 | P tempPriority2 = actual.get_priority(); 200 | V tempValue2 = actual.get_value(); 201 | 202 | actual.set_priority(actual.get_left().get_priority()); 203 | actual.set_value(actual.get_left().get_value()); 204 | 205 | actual.get_left().set_priority(tempPriority2); 206 | actual.get_left().set_value(tempValue2); 207 | 208 | actual = actual.get_left(); 209 | } else { 210 | break; 211 | } 212 | 213 | } else if (result > 0){ //Hijo izquierdo mayor 214 | result = _priorityComparator.compare(actual.get_priority(), actual.get_left().get_priority()); 215 | if (result < 0) { 216 | P tempPriority2 = actual.get_priority(); 217 | V tempValue2 = actual.get_value(); 218 | 219 | actual.set_priority(actual.get_left().get_priority()); 220 | actual.set_value(actual.get_left().get_value()); 221 | 222 | actual.get_left().set_priority(tempPriority2); 223 | actual.get_left().set_value(tempValue2); 224 | actual = actual.get_left(); 225 | } else { 226 | break; 227 | } 228 | } else { 229 | result = _priorityComparator.compare(actual.get_priority(), actual.get_right().get_priority()); 230 | if (result < 0) { 231 | P tempPriority2 = actual.get_priority(); 232 | V tempValue2 = actual.get_value(); 233 | 234 | actual.set_priority(actual.get_right().get_priority()); 235 | actual.set_value(actual.get_right().get_value()); 236 | 237 | actual.get_right().set_priority(tempPriority2); 238 | actual.get_right().set_value(tempValue2); 239 | actual = actual.get_right(); 240 | } else { 241 | break; 242 | } 243 | } 244 | 245 | } else if (!actualHasLeftChild && !actualHasRightChild){ //No tiene hijos 246 | break; 247 | } else if (actualHasLeftChild){ //Solo tiene izquierdo 248 | int result = _priorityComparator.compare(actual.get_priority(), actual.get_left().get_priority()); 249 | if (result < 0) { 250 | P tempPriority2 = actual.get_priority(); 251 | V tempValue2 = actual.get_value(); 252 | 253 | actual.set_priority(actual.get_left().get_priority()); 254 | actual.set_value(actual.get_left().get_value()); 255 | 256 | actual.get_left().set_priority(tempPriority2); 257 | actual.get_left().set_value(tempValue2); 258 | } else { 259 | break; 260 | } 261 | } else { //Solo tiene derecho 262 | int result = _priorityComparator.compare(actual.get_priority(), actual.get_right().get_priority()); 263 | if (result < 0) { 264 | P tempPriority2 = actual.get_priority(); 265 | V tempValue2 = actual.get_value(); 266 | 267 | actual.set_priority(actual.get_right().get_priority()); 268 | actual.set_value(actual.get_right().get_value()); 269 | 270 | actual.get_right().set_priority(tempPriority2); 271 | actual.get_right().set_value(tempValue2); 272 | } else { 273 | break; 274 | } 275 | } 276 | } 277 | 278 | // reducir la cantidad 279 | _count--; 280 | 281 | return tempValue; 282 | } 283 | 284 | @Override 285 | public int count() { 286 | return _count; 287 | } 288 | 289 | @Override 290 | public boolean isEmpty() { 291 | return _count == 0; 292 | } 293 | 294 | } -------------------------------------------------------------------------------- /Checkpoint Factory Design/src/UniversityController.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.IOException; 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | import java.util.Scanner; 8 | 9 | import com.fasterxml.jackson.databind.JsonNode; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | import com.fasterxml.jackson.databind.node.ArrayNode; 12 | import com.fasterxml.jackson.databind.node.ObjectNode; 13 | 14 | public class UniversityController { 15 | private static final String DATA_FILE_PATH = "data_prueba.json"; // Ruta del archivo de datos 16 | private static final List faculties = new ArrayList<>(); 17 | private static final List students = new ArrayList<>(); 18 | private static final List courses = new ArrayList<>(); 19 | private static final List auditors = new ArrayList<>(); 20 | private static final List admins = new ArrayList<>(); 21 | private static User currentUser; // Campo estático para almacenar el usuario actualmente autenticado 22 | private static final Scanner scanner = new Scanner(System.in); 23 | 24 | public static void start() { 25 | loadData(); 26 | System.out.println("Bienvenido al sistema universitario"); 27 | System.out.print("Ingrese su nombre de usuario: "); 28 | String username = scanner.nextLine(); 29 | System.out.print("Ingrese su contraseña: "); 30 | String password = scanner.nextLine(); 31 | 32 | currentUser = authenticate(username, password); // Asignar el usuario autenticado a currentUser 33 | 34 | if (currentUser != null) { 35 | System.out.println("Inicio de sesión exitoso como " + currentUser.getClass().getSimpleName()); 36 | while (true) { 37 | showOptions(currentUser); 38 | System.out.print("Seleccione una opción: "); 39 | int option = scanner.nextInt(); 40 | scanner.nextLine(); // Consumir la nueva línea después de nextInt() 41 | switch (currentUser.getClass().getSimpleName()) { 42 | case "Admin": 43 | executeAdminOption(option); 44 | break; 45 | case "Student": 46 | executeStudentOption(option); 47 | break; 48 | case "Faculty": 49 | executeFacultyOption(option); 50 | break; 51 | case "Auditor": 52 | executeAuditorOption(option); 53 | break; 54 | 55 | // Agrega casos para otro 56 | default: 57 | System.out.println("Rol de usuario no reconocido."); 58 | } 59 | if (option == 10) { 60 | saveData(); // Opción para salir 61 | break; 62 | } 63 | } 64 | } else { 65 | System.out.println("Nombre de usuario o contraseña incorrectos"); 66 | } 67 | } 68 | 69 | private static User authenticate(String username, String password) { 70 | // Recorrer todas las listas de usuarios 71 | for (Student student : students) { 72 | if (student.getUsername().equals(username) && student.getPassword().equals(password)) { 73 | return student; // Si se encuentra un estudiante con las credenciales proporcionadas 74 | } 75 | } 76 | for (Faculty faculty : faculties) { 77 | if (faculty.getUsername().equals(username) && faculty.getPassword().equals(password)) { 78 | return faculty; // Si se encuentra un profesor con las credenciales proporcionadas 79 | } 80 | } 81 | for (Auditor auditor : auditors) { 82 | if (auditor.getUsername().equals(username) && auditor.getPassword().equals(password)) { 83 | return auditor; // Si se encuentra un auditor con las credenciales proporcionadas 84 | } 85 | } 86 | for (Admin admin : admins) { 87 | if (admin.getUsername().equals(username) && admin.getPassword().equals(password)) { 88 | return admin; // Si se encuentra un administrador con las credenciales proporcionadas 89 | } 90 | } 91 | return null; // Si no se encuentra ningún usuario con las credenciales proporcionadas 92 | } 93 | 94 | 95 | private static void showOptions(User user) { 96 | if (user instanceof Admin) { 97 | showAdminOptions(); 98 | } else if (user instanceof Student) { 99 | showStudentOptions(); 100 | } else if (user instanceof Auditor) { 101 | showAuditorOptions(); 102 | } else if (user instanceof Faculty) { 103 | showFacultyOptions(); 104 | } 105 | } 106 | 107 | private static void showAdminOptions() { 108 | System.out.println("Opciones disponibles para el administrador:"); 109 | System.out.println("1. Crear curso"); 110 | System.out.println("2. Crear estudiante"); 111 | System.out.println("3. Crear profesor"); 112 | System.out.println("4. Asignar estudiante a curso"); 113 | System.out.println("5. Asignar profesor a curso"); 114 | System.out.println("6. Asignar pago a profesor"); 115 | System.out.println("7. Generar reporte de notas"); 116 | System.out.println("8. Generar reporte de pagos de estudiantes"); 117 | System.out.println("9. Exportar datos a Csv/TXT"); 118 | System.out.println("10. Salir"); 119 | // Aquí puedes agregar más opciones según sea necesario 120 | } 121 | 122 | private static void showStudentOptions() { 123 | System.out.println("Opciones disponibles para el estudiante:"); 124 | System.out.println("1. Consultar nota de una clase específica"); 125 | System.out.println("2. Realizar pago"); 126 | System.out.println("3. Consultar pagos"); 127 | System.out.println("10. Salir"); 128 | // Aquí puedes agregar más opciones según sea necesario 129 | } 130 | 131 | private static void showAuditorOptions() { 132 | System.out.println("Opciones disponibles para el auditor:"); 133 | System.out.println("1. Revisar notas"); 134 | System.out.println("2. Revisar cuotas pagadas de estudiantes"); 135 | System.out.println("3. Revisar pagos a profesores"); 136 | System.out.println("10. Salir"); 137 | // Aquí puedes agregar más opciones según sea necesario 138 | } 139 | 140 | private static void showFacultyOptions() { 141 | System.out.println("Opciones disponibles para el profesor:"); 142 | System.out.println("1. Ingresar notas de los estudiantes en una clase específica"); 143 | System.out.println("2. Cobrar pago"); 144 | System.out.println("3. Consultar historial de pagos"); 145 | System.out.println("10. Salir"); 146 | // Aquí puedes agregar más opciones según sea necesario 147 | } 148 | private static void executeAdminOption(int option) { 149 | Admin admin = (Admin) currentUser; // Suponiendo que currentUser es un campo que almacena el usuario actualmente autenticado como Admin 150 | switch (option) { 151 | case 1: 152 | // Crear curso 153 | System.out.print("Ingrese el nombre del curso: "); 154 | String courseName = scanner.nextLine(); 155 | System.out.print("Ingrese el nombre del profesor: "); 156 | String facultyUsername = scanner.nextLine(); 157 | Faculty faculty = findFacultyByUsername(facultyUsername); 158 | if (faculty != null) { 159 | admin.createCourse(courseName, faculty); 160 | System.out.println("Curso creado correctamente."); 161 | } else { 162 | System.out.println("No se encontró el profesor."); 163 | } 164 | break; 165 | case 2: 166 | // Crear estudiante 167 | System.out.print("Ingrese el nombre de usuario del estudiante: "); 168 | String studentUsername = scanner.nextLine(); 169 | System.out.print("Ingrese la contraseña del estudiante: "); 170 | String studentPassword = scanner.nextLine(); 171 | admin.createStudent(studentUsername, studentPassword); 172 | System.out.println("Estudiante creado correctamente."); 173 | break; 174 | case 3: 175 | // Crear profesor 176 | System.out.print("Ingrese el nombre de usuario del profesor: "); 177 | String professorUsername = scanner.nextLine(); // Cambiado de facultyUsername a professorUsername 178 | System.out.print("Ingrese la contraseña del profesor: "); 179 | String facultyPassword = scanner.nextLine(); 180 | admin.createFaculty(professorUsername, facultyPassword); 181 | System.out.println("Profesor creado correctamente."); 182 | break; 183 | 184 | case 4: 185 | // Asignar estudiante a curso 186 | System.out.print("Ingrese el nombre de usuario del estudiante: "); 187 | String studentUsername2 = scanner.nextLine(); 188 | System.out.print("Ingrese el nombre del curso: "); 189 | String courseName2 = scanner.nextLine(); 190 | Student student = findStudentByUsername(studentUsername2); 191 | Course course = findCourseByName(courseName2); 192 | if (student != null && course != null) { 193 | admin.assignStudentToCourse(student, course); 194 | System.out.println("Estudiante asignado correctamente al curso."); 195 | } else { 196 | System.out.println("No se encontró el estudiante o el curso."); 197 | } 198 | break; 199 | case 5: 200 | // Asignar profesor a curso 201 | System.out.print("Ingrese el nombre de usuario del profesor: "); 202 | String facultyUsername2 = scanner.nextLine(); 203 | System.out.print("Ingrese el nombre del curso: "); 204 | String courseName3 = scanner.nextLine(); 205 | Faculty faculty2 = findFacultyByUsername(facultyUsername2); 206 | Course course2 = findCourseByName(courseName3); 207 | if (faculty2 != null && course2 != null) { 208 | admin.assignFacultyToCourse(faculty2, course2); 209 | System.out.println("Profesor asignado correctamente al curso."); 210 | } else { 211 | System.out.println("No se encontró el profesor o el curso."); 212 | } 213 | break; 214 | case 6: 215 | // Asignar pago a profesor 216 | System.out.print("Ingrese el nombre de usuario del profesor: "); 217 | String facultyUsername4 = scanner.nextLine(); 218 | System.out.print("Ingrese el monto del pago: "); 219 | double amount = scanner.nextDouble(); 220 | Faculty faculty3 = findFacultyByUsername(facultyUsername4); 221 | if (faculty3 != null) { 222 | admin.assignPaymentToFaculty(faculty3, amount); 223 | System.out.println("Pago asignado correctamente al profesor."); 224 | } else { 225 | System.out.println("No se encontró el profesor."); 226 | } 227 | break; 228 | case 7: 229 | // Generar reporte de notas 230 | System.out.print("Ingrese el nombre de usuario del estudiante: "); 231 | String studentUsername3 = scanner.nextLine(); 232 | Student student2 = findStudentByUsername(studentUsername3); 233 | if (student2 != null) { 234 | admin.generateGradeReport(student2); 235 | System.out.println("Reporte de notas generado correctamente para el estudiante."); 236 | } else { 237 | System.out.println("No se encontró el estudiante."); 238 | } 239 | break; 240 | case 8: 241 | // Generar reporte de pagos de estudiantes 242 | System.out.print("Ingrese el nombre de usuario del estudiante: "); 243 | String studentUsername4 = scanner.nextLine(); 244 | Student student3 = findStudentByUsername(studentUsername4); 245 | if (student3 != null) { 246 | admin.generatePaymentReport(student3); 247 | System.out.println("Reporte de pagos generado correctamente para el estudiante."); 248 | } else { 249 | System.out.println("No se encontró el estudiante."); 250 | } 251 | break; 252 | case 9: 253 | <<<<<<< HEAD 254 | exportData(); 255 | ======= 256 | exportData(); 257 | break; 258 | >>>>>>> 8f3fe5b808288910195e19beaa10a6a48f2e674b 259 | case 10: 260 | saveData(); 261 | System.out.println("Saliendo..."); 262 | break; 263 | default: 264 | System.out.println("Opción inválida."); 265 | } 266 | } 267 | private static void executeStudentOption(int option) { 268 | Student student = (Student) currentUser; // Suponiendo que currentUser es un campo que almacena el usuario actualmente autenticado como Estudiante 269 | switch (option) { 270 | case 1: 271 | // Consultar nota de una clase específica 272 | System.out.print("Ingrese el nombre de la clase: "); 273 | String className = scanner.nextLine(); 274 | Course course2 = findCourseByName(className); 275 | // Implementa la lógica para consultar la nota del estudiante en la clase específica 276 | double grade = student.getGradeForClass(className); 277 | if (grade != -1) { 278 | System.out.println("La nota en " + className + " es: " + grade); 279 | } else { 280 | System.out.println("No se encontraron notas para la clase " + className); 281 | } 282 | break; 283 | case 2: 284 | // Realizar pago 285 | System.out.print("Ingrese el monto a pagar: "); 286 | double amount = scanner.nextDouble(); 287 | scanner.nextLine(); // Consumir la nueva línea después de nextDouble() 288 | if (student.makePayment(amount)) { 289 | System.out.println("Pago realizado correctamente."); 290 | } else { 291 | System.out.println("No se pudo realizar el pago. Fondos insuficientes."); 292 | } 293 | break; 294 | case 3: 295 | // Consultar pagos 296 | List payments = student.viewPaymentHistory(); 297 | if (!payments.isEmpty()) { 298 | System.out.println("Historial de pagos:"); 299 | for (Double payment : payments) { 300 | System.out.println("- $" + payment); 301 | } 302 | } else { 303 | System.out.println("No se encontraron pagos realizados."); 304 | } 305 | break; 306 | case 10: 307 | saveData(); 308 | System.out.println("Saliendo..."); 309 | break; 310 | default: 311 | System.out.println("Opción inválida."); 312 | } 313 | } 314 | 315 | 316 | private static void executeFacultyOption(int option) { 317 | Faculty faculty = (Faculty) currentUser; // Suponiendo que currentUser es un campo que almacena el usuario actualmente autenticado como Faculty 318 | switch (option) { 319 | case 1: 320 | // Ingresar notas de los estudiantes en una clase específica 321 | System.out.print("Ingrese el nombre de la clase: "); 322 | String className = scanner.nextLine(); 323 | System.out.print("Ingrese la nota para la clase " + className + ": "); 324 | double grade = scanner.nextDouble(); 325 | scanner.nextLine(); // Consumir la nueva línea después de nextDouble() 326 | // Implementa la lógica para que el profesor ingrese las notas de los estudiantes en la clase específica 327 | Course course = findCourseByName(className); 328 | if (course != null) { 329 | List students = course.getStudents(); 330 | for (Student student : students) { 331 | faculty.enterGrades(student, course, Collections.singletonList(grade)); 332 | } 333 | System.out.println("Notas ingresadas correctamente para la clase " + className); 334 | } else { 335 | System.out.println("No se encontró la clase " + className); 336 | } 337 | break; 338 | case 2: 339 | // Cobrar pago 340 | System.out.print("Ingrese el nombre de usuario del estudiante: "); 341 | String studentUsername = scanner.nextLine(); 342 | Student student = findStudentByUsername(studentUsername); 343 | if (student != null) { 344 | System.out.print("Ingrese el monto a cobrar: "); 345 | double amountToCollect = scanner.nextDouble(); 346 | faculty.collectPayment(student, amountToCollect); 347 | System.out.println("Pago cobrado correctamente."); 348 | } else { 349 | System.out.println("Estudiante no encontrado."); 350 | } 351 | break; 352 | case 3: 353 | // Consultar historial de pagos 354 | System.out.println("Historial de pagos:"); 355 | faculty.viewPaymentHistory(); 356 | break; 357 | case 10: 358 | saveData(); 359 | System.out.println("Saliendo..."); 360 | break; 361 | default: 362 | System.out.println("Opción inválida."); 363 | } 364 | } 365 | 366 | 367 | private static void executeAuditorOption(int option) { 368 | Auditor auditor = (Auditor) currentUser; // Suponiendo que currentUser es un campo que almacena el usuario actualmente autenticado como Auditor 369 | switch (option) { 370 | case 1: 371 | // Revisar notas 372 | auditor.reviewGrades(); 373 | break; 374 | case 2: 375 | // Revisar cuotas pagadas de estudiantes 376 | auditor.reviewStudentPayments(); 377 | break; 378 | case 3: 379 | // Revisar pagos a profesores 380 | auditor.reviewFacultyPayments(); 381 | break; 382 | case 10: 383 | saveData(); 384 | System.out.println("Saliendo..."); 385 | break; 386 | default: 387 | System.out.println("Opción inválida."); 388 | } 389 | } 390 | 391 | private static Faculty findFacultyByUsername(String username) { 392 | // Supongamos que tienes una lista de profesores llamada 'faculties' 393 | for (Faculty faculty : faculties) { 394 | if (faculty.getUsername().equals(username)) { 395 | return faculty; 396 | } 397 | } 398 | return null; // Retorna null si no se encuentra ningún profesor con el nombre de usuario dado 399 | } 400 | private static Student findStudentByUsername(String username) { 401 | // Supongamos que tienes una lista de profesores llamada 'faculties' 402 | for (Student student : students) { 403 | if (student.getUsername().equals(username)) { 404 | return student; 405 | } 406 | } 407 | return null; // Retorna null si no se encuentra ningún profesor con el nombre de usuario dado 408 | } 409 | private static Auditor findAuditorByUsername(String username) { 410 | // Supongamos que tienes una lista de profesores llamada 'faculties' 411 | for (Auditor auditor : auditors) { 412 | if (auditor.getUsername().equals(username)) { 413 | return auditor; 414 | } 415 | } 416 | return null; // Retorna null si no se encuentra ningún profesor con el nombre de usuario dado 417 | } 418 | private static Admin findAdminByUsername(String username) { 419 | // Supongamos que tienes una lista de profesores llamada 'faculties' 420 | for (Admin admin : admins) { 421 | if (admin.getUsername().equals(username)) { 422 | return admin ; 423 | } 424 | } 425 | return null; // Retorna null si no se encuentra ningún profesor con el nombre de usuario dado 426 | } 427 | private static Course findCourseByName(String name) { 428 | // Supongamos que tienes una lista de profesores llamada 'faculties' 429 | for (Course course : courses) { 430 | if (course.getCourseName().equals(name)) { 431 | return course ; 432 | } 433 | } 434 | return null; // Retorna null si no se encuentra ningún profesor con el nombre de usuario dado 435 | } 436 | private static void exportData() { 437 | System.out.println("Seleccione el formato de exportación:"); 438 | System.out.println("1. Exportar a TXT"); 439 | System.out.println("2. Exportar a CSV"); 440 | System.out.print("Seleccione una opción: "); 441 | int exportOption = scanner.nextInt(); 442 | scanner.nextLine(); // Consumir la nueva línea después de nextInt() 443 | 444 | IDataSource dataSource; 445 | switch (exportOption) { 446 | case 1: 447 | dataSource = DataSourceFactory.getDataSourceInstance(DataSourceFactory.TXT_TYPE); 448 | dataSource.saveData(collectAllData(), "exported_data.txt"); 449 | System.out.println("Datos exportados a TXT correctamente."); 450 | break; 451 | case 2: 452 | dataSource = DataSourceFactory.getDataSourceInstance(DataSourceFactory.CSV_TYPE); 453 | dataSource.saveData(collectAllData(), "exported_data.csv"); 454 | System.out.println("Datos exportados a CSV correctamente."); 455 | break; 456 | default: 457 | System.out.println("Opción inválida."); 458 | } 459 | } 460 | private static List collectAllData() { 461 | List allData = new ArrayList<>(); 462 | allData.addAll(collectUserData()); 463 | allData.addAll(collectCourseData()); 464 | // Añade más listas según sea necesario (por ejemplo, auditors, admins, etc.) 465 | return allData; 466 | } 467 | 468 | private static List collectUserData() { 469 | List userData = new ArrayList<>(); 470 | 471 | // Estudiantes 472 | for (Student student : students) { 473 | userData.add(new String[] {student.getUsername(), student.getPassword()}); 474 | } 475 | 476 | // Profesores 477 | for (Faculty faculty : faculties) { 478 | userData.add(new String[] {faculty.getUsername(), faculty.getPassword()}); 479 | } 480 | 481 | // Auditores 482 | for (Auditor auditor : auditors) { 483 | userData.add(new String[] {auditor.getUsername(), auditor.getPassword()}); 484 | } 485 | 486 | // Administradores 487 | for (Admin admin : admins) { 488 | userData.add(new String[] {admin.getUsername(), admin.getPassword()}); 489 | } 490 | 491 | return userData; 492 | } 493 | 494 | private static List collectCourseData() { 495 | List courseData = new ArrayList<>(); 496 | for (Course course : courses) { 497 | courseData.add(new String[] {course.getCourseName()}); 498 | } 499 | // Añade más información de cursos según sea necesario 500 | return courseData; 501 | } 502 | 503 | private static void saveData() { 504 | try { 505 | ObjectMapper objectMapper = new ObjectMapper(); 506 | ObjectNode rootNode = objectMapper.createObjectNode(); 507 | 508 | // Convertir cada lista a un ArrayNode y luego agregarlo al objeto raíz 509 | ArrayNode studentsArray = objectMapper.valueToTree(students); 510 | ArrayNode facultiesArray = objectMapper.valueToTree(faculties); 511 | ArrayNode coursesArray = objectMapper.valueToTree(courses); 512 | ArrayNode auditorsArray = objectMapper.valueToTree(auditors); 513 | ArrayNode adminsArray = objectMapper.valueToTree(admins); 514 | 515 | rootNode.set("students", studentsArray); 516 | rootNode.set("faculties", facultiesArray); 517 | rootNode.set("courses", coursesArray); 518 | rootNode.set("auditors", auditorsArray); 519 | rootNode.set("admins", adminsArray); 520 | 521 | // Escribir el JSON en el archivo 522 | objectMapper.writeValue(new File(DATA_FILE_PATH), rootNode); 523 | 524 | System.out.println("Datos guardados correctamente en el archivo: " + DATA_FILE_PATH); 525 | } catch (IOException e) { 526 | e.printStackTrace(); 527 | System.out.println("Error al guardar los datos."); 528 | } 529 | } 530 | 531 | 532 | 533 | private static void loadData() { 534 | try { 535 | ObjectMapper objectMapper = new ObjectMapper(); 536 | JsonNode rootNode = objectMapper.readTree(new File(DATA_FILE_PATH)); 537 | 538 | // Cargar listas de estudiantes, profesores, cursos, etc. desde el archivo 539 | students.clear(); 540 | faculties.clear(); 541 | courses.clear(); 542 | auditors.clear(); 543 | admins.clear(); 544 | 545 | // Cargar estudiantes 546 | students.addAll(Arrays.asList(objectMapper.treeToValue(rootNode.get("students"), Student[].class))); 547 | 548 | // Cargar profesores 549 | faculties.addAll(Arrays.asList(objectMapper.treeToValue(rootNode.get("faculties"), Faculty[].class))); 550 | 551 | // Cargar cursos 552 | courses.addAll(Arrays.asList(objectMapper.treeToValue(rootNode.get("courses"), Course[].class))); 553 | 554 | // Cargar auditores 555 | auditors.addAll(Arrays.asList(objectMapper.treeToValue(rootNode.get("auditors"), Auditor[].class))); 556 | 557 | // Cargar administradores 558 | admins.addAll(Arrays.asList(objectMapper.treeToValue(rootNode.get("admins"), Admin[].class))); 559 | 560 | System.out.println("Datos cargados correctamente desde el archivo: " + DATA_FILE_PATH); 561 | } catch (IOException e) { 562 | e.printStackTrace(); 563 | System.out.println("Error al cargar los datos."); 564 | } 565 | } 566 | } 567 | 568 | --------------------------------------------------------------------------------