Archive for 2014
November 28th, 2014
SDP03 Exercise 25
En esta aplicación lo principal fue el conteo de tiempo de ejecución de los programas en tres clases GameArray donde los datos fueron obtenidos y acomodados.
Nos pudimos dar cuenta de las herramientas usadas en JAVA para el conteo del tiempo del sistema; características cuya importancia reside en que obtenemos el tiempo de
eficiencia de un programa, invitándonos a programar de la manera más lógica posible y lograr así mejor rendimiento en los programas.
November 28th, 2014
SDP03 Exercise 24
En este ejercicio trabajamos en solo una clase donde lo principal fue realizar algunos cálculos mediante datos obtenidos
de un archivo llamado data.txt.
Los conceptos de columnas y renglones fueron necesarios, además de las estructuras for y manejo de streams.
Se leen los valores y se asignan a un arreglo, posteriormente se promedian y suman, además de que se muestran
al usuario ordenados en una cuadrícula. Semejante a los principios que nos permitieron el manejo de datos en ejercicios anteriores.
SDP03 Exercise 24
En este ejercicio trabajamos en solo una clase donde lo principal fue realizar algunos cálculos mediante datos obtenidos
de un archivo llamado data.txt.
Los conceptos de columnas y renglones fueron necesarios, además de las estructuras for y manejo de streams.
Se leen los valores y se asignan a un arreglo, posteriormente se promedian y suman, además de que se muestran
al usuario ordenados en una cuadrícula. Semejante a los principios que nos permitieron el manejo de datos en ejercicios anteriores.
November 28th, 2014
SDP03 Exercise 23
¿Qué preguntas tienes sobre el material que hemos cubierto en la clase?
Hemos aprendido mucho sobre programación a lo largo del curso. A lo largo de éste hemos ido resolviendo nuestras dudas y cada vez nos hemos podido
hacer preguntas más complicadas. Hemos investigado y analizado los comentarios de las aplicaciones para comprender, de manera particular hemos buscado alternativas
para algunos ejercicios.
¿Qué has aprendido en semestre hasta ahora?
Hemos aprendido mucho acerca de arreglos y otras estructuras de datos. A la par hemos podido comprender la gran aplicación que tienen en una gran cantidad de
programas y como ejemplos podemos considerar los ejercicios que hemos realizado. Ahora conocemos más funciones y sabemos cómo hacer uso de ellas para la resolución de
problemas.
SDP03 Exercise 23
¿Qué preguntas tienes sobre el material que hemos cubierto en la clase?
Hemos aprendido mucho sobre programación a lo largo del curso. A lo largo de éste hemos ido resolviendo nuestras dudas y cada vez nos hemos podido
hacer preguntas más complicadas. Hemos investigado y analizado los comentarios de las aplicaciones para comprender, de manera particular hemos buscado alternativas
para algunos ejercicios.
¿Qué has aprendido en semestre hasta ahora?
Hemos aprendido mucho acerca de arreglos y otras estructuras de datos. A la par hemos podido comprender la gran aplicación que tienen en una gran cantidad de
programas y como ejemplos podemos considerar los ejercicios que hemos realizado. Ahora conocemos más funciones y sabemos cómo hacer uso de ellas para la resolución de
problemas.
November 28th, 2014
SDP03 Exercise 22
En este ejercicio continuamos mejorando el comportamiento de nuestra aplicación ejecutando las reglas del juego.
Generamos varias rutinas en nuestro código para administrar los valores y cómo se activarán los métodos de acuerdo a las acciones de los usuarios.
Se validaron los movimientos y la manera de interpretar los desplazamientos y asignación de los dígitos.
Se definieron los valores y los valores contenidos en las cajas de texto y los valores de los ComboBox.
SDP03 Exercise 22
En este ejercicio continuamos mejorando el comportamiento de nuestra aplicación ejecutando las reglas del juego.
Generamos varias rutinas en nuestro código para administrar los valores y cómo se activarán los métodos de acuerdo a las acciones de los usuarios.
Se validaron los movimientos y la manera de interpretar los desplazamientos y asignación de los dígitos.
Se definieron los valores y los valores contenidos en las cajas de texto y los valores de los ComboBox.
November 28th, 2014
SDP03 Exercise 21
A partir de este momento empezamos a utilizar la parte gráfica del programa para el juego de SUDOKU. Es importante porque esta es la parte
que puede resultar atractiva para el usuario. De igual manera, lo anterior es indispensable para coordinar las acciones del programa y las reglas lógicas
que regirán la aplicación mientras el usuario lo esté usando.
Para iniciarlo se dispone de una caja de texto donde el usuario escribe manualmente el nombre del archivo XML y los números por defecto son agregados en
las casillas de selección múltiple o ComboBox de la GUI.
En la clase Puzzle se manejan otras características del aspecto gráfico de la aplicación manejando los números y administrando la disposición de los dígitos acorde
a una cuadrícula e interfaz gráfica del juego.
SDP03 Exercise 21
A partir de este momento empezamos a utilizar la parte gráfica del programa para el juego de SUDOKU. Es importante porque esta es la parte
que puede resultar atractiva para el usuario. De igual manera, lo anterior es indispensable para coordinar las acciones del programa y las reglas lógicas
que regirán la aplicación mientras el usuario lo esté usando.
Para iniciarlo se dispone de una caja de texto donde el usuario escribe manualmente el nombre del archivo XML y los números por defecto son agregados en
las casillas de selección múltiple o ComboBox de la GUI.
En la clase Puzzle se manejan otras características del aspecto gráfico de la aplicación manejando los números y administrando la disposición de los dígitos acorde
a una cuadrícula e interfaz gráfica del juego.
November 28th, 2014
SDP03 Exercise 20
In this exercise we continued to improve the behavior of our program to play SUDOKU considering how important is to order the numbers
and to know how they must act according to the user movements.
There were some methods that were modified, in whichSquare() we wrote some useful lines to be able to locate the numbers according to the
square that they could be in. We use the row and column values to identify the digit position.
There's other method named isValidCell() in which we wrote the code lines in order to verify if the cell is valid since it must not be repeated.
We tried to use the for iterative structures so far, but we later changed to lists or sets that keep data collections so that they are better managed.
SDP03 Exercise 20
In this exercise we continued to improve the behavior of our program to play SUDOKU considering how important is to order the numbers
and to know how they must act according to the user movements.
There were some methods that were modified, in whichSquare() we wrote some useful lines to be able to locate the numbers according to the
square that they could be in. We use the row and column values to identify the digit position.
There's other method named isValidCell() in which we wrote the code lines in order to verify if the cell is valid since it must not be repeated.
We tried to use the for iterative structures so far, but we later changed to lists or sets that keep data collections so that they are better managed.
November 28th, 2014
SDP03 Exercise 19
In this exercise the aim was to write the correct method in order to display the data read or scanned from
the XML file in order of 9 squares with 9 numbers in each square, so that they're 81 numbers wich form the
game known as SUDOKU.
The most important thing was to detect, in the class GameArray, how the program read the data through for structures, after that we
wrote some lines to order the numbers or digits from 0 to 9 in the corresponding squares.
We used several arrays and methods to get the values, the main method that we modified was "gameToString()" because
in it we ordered the information using functions like append to get the characters of the numbers read from the XML file
through a stream.
SDP03 Exercise 19
In this exercise the aim was to write the correct method in order to display the data read or scanned from
the XML file in order of 9 squares with 9 numbers in each square, so that they're 81 numbers wich form the
game known as SUDOKU.
The most important thing was to detect, in the class GameArray, how the program read the data through for structures, after that we
wrote some lines to order the numbers or digits from 0 to 9 in the corresponding squares.
We used several arrays and methods to get the values, the main method that we modified was "gameToString()" because
in it we ordered the information using functions like append to get the characters of the numbers read from the XML file
through a stream.
SDP04 Project 01
Square Root of Two
November 21st, 2014
After solving the before four exercises, we could solve the first SDP04 project
that could only be solved applying the previous knowledge and abilities (also examples).
In this project we started with an application that solved the square root of the number two (2), nevertheless, there are some things that we've got to change in order to get our application solve square root of other numbers using the Newton's method.
When we had just started to read the problem, we noticed that the problem was working effectively in some situations but, on the other hand, the results were wrong when we wrote numbers that have a exact square root.
Our instructor gave us some advices to notice what we had got to do.
The first thing that we did was to modify the UNumber class by adding a public method named sqr with a parameter named decimales.
We modified the three first variables changing the mantissa, the characteristic, and the sign, for example; creating the variable sig, we noticed that it was necessary to change values in the constructor because the number in the characteristic depends on decimales parameter.
We also need precision, so that we added ten units to each line in which we used the variable decimales.
Then, we wrote the code that we've been using to calculate the Square Root according to Newton's method. We only had to change some values using the variables dp (that's named after decimal point), s (that's named after sign), and d (according to the mantissa dimension).
Once done this, we create an object from UNumber class into TestMainline class to call
the method that we created in UNumber class, remembering that we have modified the method and we have to give a type int parameter on calling the method.
We finally wrote a line that shows the result of the operation onto the screen.
After that, we proved the app and we noticed that it works correctly, now it doesn't only calculates the square root of two but of other numbers, this was thanks to the variable decimales that helps the computer to calculate the solution for a lot of numbers, giving the most close numbers as result .
SDP04 - Ejercicio 05
Miércoles 12 de noviembre de 2014
PROPÓSITO
El propósito de este ejercicio es calcular con un programa en C para la medición del
desempeño.
En este ejercicio utilizamos tanto las implementaciones de C y Java del
programa que calcula la raíz cuadrada de un número usando dobles.
Resultados
C es más rápido que Java.
Los Puntos de Referencia
Contra toda lógica, la única área en la que Java puede ser
tan rápido como C ++ es un punto de referencia típica. Si usted necesita para
calcular número enésimo de Fibonacci o ejecutar Linpack, no hay ninguna razón
por qué Java no puede ser tan rápido como C ++. Mientras todo el cálculo se
queda en una clase y sólo utiliza los tipos de datos primitivos como int y
doble, el compilador Java es en igualdad de condiciones con el compilador de C
++.
En el mundo real
En el momento de empezar a usar objetos en su programa, Java
pierde el potencial de optimización. En esta sección se enumeran algunas de las
razones por qué.
1. Todos los objetos se asignan en el montón
Java sólo asigna los tipos de datos primitivos como int y
referencias dobles y objeto en la pila. Todos los objetos se asignan en el
montón.
Para objetos grandes que normalmente tienen la semántica de
identidad, esto no es una desventaja. Programadores de C ++ también asignar
estos objetos en el montón. Sin embargo, para objetos pequeños con semántica de
valor, esta es una importante causa de muerte rendimiento.
2. Muchos de los yesos
Con el advenimiento de las plantillas, los programadores
buena C ++ han sido capaces de evitar yesos casi completamente en programas de
alto nivel. Por desgracia, Java no tiene plantillas, por lo que el código de
Java es normalmente llena de moldes.
3. Aumento de la memoria Uso
Programas Java utilizan casi el doble de la memoria de
programas comparables C ++ para almacenar los datos. Hay tres razones para
ello:
Los programas que utilizan la recolección de basura
automática suelen utilizar aproximadamente un 50% más de memoria que los
programas que hacen la gestión de memoria manual.
Muchos de los objetos que se asignan en la pila en C ++ se
asignarán en el montón de Java.
Objetos Java serán más grandes, debido a todos los objetos
que tienen una tabla virtual además de soporte para primitivas de
sincronización.
Una huella de memoria más grande aumenta la probabilidad de
que las partes del programa se pueden intercambiar en el disco. Y el uso del
archivo de intercambio mata la velocidad como ninguna otra cosa.
4. La falta de control sobre los detalles
Java fue diseñado intencionalmente para ser un lenguaje
sencillo. Muchas de las características disponibles en C ++ que le dan el
control del programador sobre los detalles fueron despojados deliberadamente de
distancia.
Por ejemplo, en C ++ se puede implementar esquemas que
mejoren la localidad de referencia. O asignar y muchos objetos libres de una
vez. O jugar trucos punteros para hacer el acceso más rápido miembro. Etcétera
Ninguno de estos sistemas están disponibles en Java.
5. No hay optimizaciones de Alto Nivel
Los programadores lidiar con conceptos de alto nivel. A
diferencia de ellos, los compiladores se ocupan exclusivamente de los de bajo
nivel. Para un programador, una clase llamada Matrix representa un concepto de
alto nivel diferente de una clase denominada Vector. Para un compilador, esos
nombres son sólo las entradas en la tabla de símbolos. Lo que le importa son
las funciones que contienen esas clases, y las sentencias dentro de esas
funciones.
Conclusión
Java, con las características del lenguaje actual, nunca
será tan rápido como C ++. Esto más o menos significa que no es una buena
opción para el software de alto rendimiento y la arena COTS altamente
competitivo. Pero su pequeña curva de aprendizaje, su perdón y su gran
biblioteca estándar la convierten en una buena opción para algunos programas de
pequeño y mediano tamaño de la casa y hecha a la medida.
SDP04 - Exercise 04
November 11th, 2014
The activity we've done today was about calculating the square root of the number 2 using the Newton's method. This consists in getting closer and closer to the correct number through for iterations and number conversions.
We used some code lines that are found in last projects, which helped us to write the program; we could just rewrite the code according to the C++ programming language.
The result was correct and, it even showed us the most significant digits that are considered by the program in solving the problem.
SDP04 - Ejercicio 03
Martes 11 de noviembre de 2014
El ejercicio 03 fue una actividad en la que continuamos con el empleo de las variables y operadores de las que el lenguaje de programación C++ y C disponen para realizar diferentes cálculos y operaciones útiles en las operaciones correspondientes.
También notamos la gran utilidad de los signos de operación y de asignación empleados para generar un flujo de programa.
El programa consta de un ciclo que va desde 0 hasta ser igual o menor a 10, por lo que se repite 11 veces, durante ese ciclo una variable (sum) va incrementandose en la cantidad del contador y sólo se muestran en pantalla los resultados cuyo resultado al ser divididos entre 3 sea idéntico a 0.
Para terminar la aplicación, se suman todos los valores que cumplen la condición anterior y el resultado se muestra en pantalla.
El resultado lo podemos visualizar en la siguiente pantalla:
SDP04 - Ejercicio 02
Martes 11 de noviembre de 2014
Iniciando curso de iCarnegie Software Development Program (SDP) 04, que analiza estructuras de datos e implementa aplicaciones sobre la misma.
El ejercicio 02 es corto pero tuvo como finalidad nuestra introducción a este Lenguaje de Programación (C++) a partir del cual se diseñó Java, ambos son lenguajes de programación de alto nivel y hacen uso de la POO (Programación Orientada a Objetos).
Analizamos ejemplos de sintaxis y creamos el tan recurrido programa para imprimir en pantalla el mensaje "¡Hola Mundo!".
Vimos elementos del programa; la llamada a librerías y las sentencias y comandos que nos proporcionan las librerías que se pueden importar.
Inexact Unit Calculator
November 04, 2014
El proyecto 2 fue una evaluación que contenía pruebas en forma de pequeños problemas reunidos de todos los ejercicios evaluados anteriormente.
La declaración de los método de covertOperando fue necesario modificaros a una variable para almacenar un conjunto de operaciones de clase UNumber: private UNumber mediante la sintaxis siguiente:
private UNumber convertOperand2()
{
return new UNumber );
}
Fue necesario modificar el arreglo de igual manera a un formato new UNumber (1", -50, true) a una variable para almacenar un conjunto de operaciones de clase UNumber y resolver el problema. Despues agregamos un If (limit.greaterThat(theoperando))
Pero nos encontramos a un problema, el cual fue que la calculadora no podia dividir, volvimos al código y cambiamos el operando de la divisiónn se declara de una forma diferente con base en los parámetros que acepta el método correspondiente para realizar las operaciones empleando valores UNumber.
Otro aspecto importante a considerar fue el manejo de los tipos de datos UNumber que muestra valores más exactos acorde a los criterios definidos por el usuario.
Otro aspecto importante a considerar fue el manejo de los tipos de datos UNumber que muestra valores más exactos acorde a los criterios definidos por el usuario.
SDP03 Exercise 09
Octubre 24, 2014
El ejercicio 09 fue una continuación del ejercicio anterior.
La estructuras de inserción de datos presentan la sintaxis siguiente:
UNumber two = new UNumber("2", 1, true);
A través de la definición de una variable mediante los argumentos anteriores se cuenta con la información suficiente para poder efectuar el algoritmo y obtener la raíz cuadrada de un valor dado.
Fue necesario recurrir a una variable para almacenar un conjunto de operaciones de clase UNumber y resolver el problema.
Como resultado obtuvimos los valores de raíz cuadrada del valor indicado como parámetro.
Analizamos que la asignación de valores de una variable a otra debe ser a través de una nueva instancia de la variable para que las operaciones que se realicen sobre una variable no afecten a los otra.
SDP03 Exercise 08
Octubre 24, 2014
Este ejercicio es la base para la continuación del siguiente ejercicio; ambos tratan de encontrar la solución a la raíz cuadrada de un número.
En esta aplicación fue necesario entender el funcionamiento del procedimiento para calcular la raíz cuadrada a partir de un algoritmo distinto al que empleamos tradicionalmente.
Se declaró un ciclo en el que se van obteniendo números aproximados a la solución, es decir, números que al multiplicarse por sí mismos se acercan cada vez más al número buscado. En esta parte fue importante seguir una serie de operaciones necesarias para el cálculo.
Fue importante notar que no se aplican los operadores de la misma manera que con valores double, float, byte o int sino que, por pertenecer a la clase UNumber, emplea operandos distintos. Métodos proporcionados por la clase para efectuar las operaciones.
Algo que impidió en un momento que halláramos la solución fue que la asignación de valores debe darse o llevarse a cabo de manera distinta, además de que declaramos las variables adecuadas para cuantificar los valores.
SDP03 Exercise 07
Octubre 24, 2014
En este ejercicio tomamos como base para el código el ejercicio 06, la diferencia fue que en esta ocasión había que manejar valores de mayor precisión, es decir, valores de la clase UNumber que acompañaba el paquete de clases.
Un error que corregimos desde el inicio fue el nombre del paquete escrito en la clase UNumber, ya que hacía referencia a un paquete no incluido en nuestro proyecto JAVA.
Agregamos el código del ejercicio anterior declarando las variables mediante constructores UNumber y siguiendo los parámetros adecuados que permitieran el buen funcionamiento del proyecto. Esto fue algo que aprendimos con los distintos proyectos de este módulo; manejar adecuadamente la clase UNumber hecha para tener una mayor precisión en los resultados de operaciones matemáticas y cálculos más complejos.
Declarar las variables inicializadas con los valores correspondientes, ahora con valores pertenecientes a la clase UNumber, la sintaxis es:
UNumber [nombreVariable] = new UNumber(valorInicial);
Durante el proceso de codificación, manejamos el intercambio entre valores String, char, byte e int empleando herramientas de conversión posibles e incluidas en la paquetería JAVA.
Modificamos algunas condiciones IF porque era necesario adecuarlas a las nuevas especificaciones y obtención de valores.
La ejecución del programa fue exitoso y mostró el resultado esperado.
SDP03 Exercise 06
October 24th, 2014
In this exercise we had to add some code lines in order to make the application to show to the user the number that are written in the datafile.txt file. The purpose is that the results are presented organized by mantissa, characteristic, and sign.
By reading the instructions, we understood what a mantissa is and what the characteristic expresses. Other thing that we had to consider was that the sign must be managed like a Char type variable because the compiler tends to multiplicative them and the result shown in the screen is incorrect.
The first thing we do was to declare several variables; type char to manage the signs, String to manage the mantissa and characteristic values, byte to declare a counter used in the process, and boolean to define different points that will work like a reference to solve the different situations according to the numbers read from the text file.
Then, we wrote some lines in a while cycle to read the numbers and we keep it on a array that is divided into char values by using the [array name].charAt(counter variable);
After that, we declared a switch structure that worked by analyzing the set of conditions given and following a corresponding path to the sign or exponent found in the data file.
Next, we added some if's above the switch structure that are going to be evaluated according to the elements found in the code lines.
Finally, the lines to show the result in the screen were already written, we only added the values to be shown.
SDP03 - Exercise 05
Octubre 24, 2014
Este ejercicio consistió en calcular el promedio de una serie de números contenidos en un archivo de texto (.txt) que el programa es capaz de leer. A partir de tales valores se calculan las sumas y divisiones correspondientes al cálculo del promedio de una cantidad de números.
Los operadores funcionaban ya que se estaban empleando valores double, por tanto el resultado era expresado con diferente cantidad de decimales y se aplicaron las reglas de redondeo por defecto, por lo tanto la precisión variaba un tanto; algo que para valores científicos podía ser inadecuado.
La solución fue utilizar una clase proporcionada por iCarnegie llamada UNumber, donde se incluyen desde variables y tipos de datos diferentes hasta métodos correspondientes a los tipos de datos relacionados.
A lo largo del ejercicio descubrimos cómo llevar a cabo actividades esenciales tales como declarar las variables, cargar valores, empleo de argumentos y, en general, cómo manipular los objetos creados a partir de la clase UNumber.
Now, we are presenting some pictures that show the results in the movements for the maze runner to get the finish line.
The path that the maze runner follows is determinated by the instructions in the method makemove().
We decided to add the following directions:
- Left (0,-1)
- Upwards (-1,0)
- Right (0,1)
- Downwards (1,0)
The image above show the result, we found out one of the quickest path to solve the maze.
September 30th, 2014
iCarnegie Project 01
Maze Runner
Today's activity was to solve the iCarnegie Project 01 in which the aim was to make the maze runner to leave the start line in order to get to the finish line. This will be solved through the algorithm that specifies the directions (upwards, downwards, left, and right) that the maze runner will follow.
The code lines were already started by iCarnegie developers, our task was to complete the code so that the application works properly.
- The first thing we do was to analyze the code lines and to run the application to see the result and discover what we could do to improve it.
- Then, we opened our four exercise projects to identify the methods that we might use in order to solve the errors and to add the functionality.
- According to the instructions, we placed our code lines in the pointed places.
- We ran the program several times and we could get the aim, that the maze runner (in a three-asterisk form) would walk through the paths and, finally, could get the finish line.
- We verified that the order of the movement methods was indispensable to determinate how fast or how slow the maze runner solved the maze. So, we tried different ways to order the direction methods and, finally, we found a very useful algorithm that goes from the start line up to the finish line without returning or walking onto the same place more than once.
Throughout the activity, we discovered how to use the methods and apply the logical structure to solve the problem.
Miércoles 24 de septiembre de 2014
Ejercicio 04 de SDP03
En este ejercicio de iCarnegie se nos presentó un programa que ya permitía mover, a través de las coordenadas, la ubicación del maze runner, sin embargo, lo que se buscaba era que la marca o huella de que éste había pasado por ahí quedara marcado con un número 1 y que, se fuera sumando 1 más cada vez que el maze runner pasara encima.package maze;
import java.io.File;
import java.util.Scanner;
/**
* @author Lynn Robert Carter based on work by Park
*
*/
public class Exercise04 {
private static final String dataPath = "mazedata.txt";
private static int[][] cell;
private static int maxRow = 0; // These are the height and width of the maze
private static int maxCol = 0;
private static final int WALL = -1; // These constants are the encoding used to represent the maze
private static final int START = -2; // A zero and positive values are pathways. A positive value
private static final int GOAL = -3; // specifies how many times the MazeRunner has left this position
private static int currentRow;
private static int currentCol;
/****
* This method returns false if the specified location is outside of the maze or the cell is a WALL, a START, or
* a GOAL. The method works on a delta from the current location of the MazeRunner (e.g., -1, 0, or +1)
*
* @param rDelta - row offset
* @param cDelta - column offset
* @return - true if this is not a wall, false if this is a a WALL, a START, or a GOAL
*/
private static boolean notWall(int rDelta, int cDelta) {
if (currentRow+rDelta < 0 || currentRow+rDelta >= maxRow || currentCol+cDelta < 0 || currentCol+cDelta >= maxCol)
return false;
return cell[currentRow+rDelta][currentCol+cDelta] >= 0;
}
/*****
* This method returns the integer value for a path that indicates how many times this cell has been left. If the
* indicated cell is a WALL, a START, or a GOAL, the method returns a very large positive value. The method works
* on a delta from the current location of the MazeRunner (e.g., -1, 0, or +1)
*
* @param rDelta - row offset
* @param cDelta - column offset
* @return - the integer value of the number of marks for this cell.
*/
private static int getMarks(int rDelta, int cDelta) {
if (currentRow+rDelta < 0 || currentRow+rDelta >= maxRow || currentCol+cDelta < 0 || currentCol+cDelta >= maxCol) return 9999999;
if (cell[currentRow+rDelta][currentCol+cDelta] < 0) return 9999999;
return cell[currentRow+rDelta][currentCol+cDelta];
}
/*****
* This method returns the context of a cell. The method works on a delta from the current location of the
* MazeRunner (e.g., -1, 0, or +1). If the specified location is outside of the maze, the value returned is
* a WALL.
*
* @param rDelta - row offset
* @param cDelta - column offset
* @return - the content of a maze cell given the delta values
*/
private static int getContents(int rDelta, int cDelta) {
if (currentRow+rDelta < 0 || currentRow+rDelta >= maxRow || currentCol+cDelta < 0 || currentCol+cDelta >= maxCol)
return WALL;
return cell[currentRow+rDelta][currentCol+cDelta];
}
/*****
* This is the method you need to write. The above methods can help make this method much easier to write.
*/
public static boolean makeMove(){
if(getContents(0,1)==GOAL||getContents(-1,0)==GOAL||
getContents(1,0) ==GOAL || getContents(0,-1) == GOAL)return false;
if(notWall(1,0)){
if(getMarks(1,0)<=getMarks(-1,0)&&getMarks(1,0)<=getMarks(0,1)&&
getMarks(1,0)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
}
if(notWall(0,1)){
if(getMarks(1,0)<=getMarks(-1,0)&&getMarks(0,1)<=getMarks(0,1)&&
getMarks(0,1)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
}
if(notWall(-1,0)){
if(getMarks(-1,0)<=getMarks(-1,0)&&getMarks(-1,0)<=getMarks(0,1)&&
getMarks(-1,0)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
}
if(notWall(0,-1)){
if(getMarks(0,-1)<=getMarks(-1,0)&&getMarks(0,-1)<=getMarks(0,1)&&
getMarks(0,-1)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
//System.out.println("The makeMove method was called.");
}
return false;
}
/**
* Create a String representation of the maze
*/
private static String mazeToString(){
return mazeToString(0, maxRow-1, 0, maxCol-1);
}
/*****
* Convert some to all of the maze to a String for output
*
* @param strtRow The index of the row to start the display
* @param GOALRow The index of the row to GOAL the display
* @param strtCol The index of the column to start the display
* @param GOALCol The index of the column to GOAL the display
* @return The String that represents the display
*/
private static String mazeToString(int strtRow, int GOALRow, int strtCol, int GOALCol){
// Start by displaying the column numbers
String result = " ";
for (int c = strtCol; c <= GOALCol; c++)
if (c < 10) result += " " + c + " ";
else result += " " + c + " ";
result += '\n';
// Then work through the rows, one at a time
for (int r = strtRow; r <= GOALRow; r++) {
// Label the row with a row number
if (r < 10) result += " " + r + " ";
else result += " " + r + " ";
// Then display the row
for (int c = strtCol; c <= GOALCol; c++) {
// If the specified maze cell is that of the Maze Runner, display a special symbol
if (currentRow == r && currentCol == c) result += " ** ";
else
// Otherwise, display a representation for that cell
switch (cell[r][c]) {
case -1:
result += "++++";
break;
case -2:
result += "++S+";
break;
case -3:
result += "++G+";
break;
case 0:
result += " ";
break;
default:
int v = Math.min(9, cell[r][c]);
result += " " + v + " ";
break;
}
}
// Add a new line at the end of each row
result += '\n';
}
// Display a key to help the user understand what is being displayed
result += "\nKey: ++++ = Wall; ++S+ = Start; ++G+ = Goal; ** = Maze Runner; 1 - 9 path with that many chalk marks.\n";
// Return the resulting String to the caller
return result;
}
/*****
* This method reads in a maze. If the maze is not valid, it displays the reason and terminates. If the maze is valid,
* it displays the maze using the method mazeToString.
*/
private static void readTheMaze() {
try {
// Set up the Scanner object to read in the maze.
Scanner scanner = new Scanner(new File(dataPath));
String line = scanner.nextLine();
Scanner s = new Scanner(line);
// Read in the number of rows and columns
maxCol = s.nextInt();
maxRow = s.nextInt();
// Create the maze and assume it is valid
cell = new int[maxCol][maxRow];
boolean isValidMaze = true;
// Read in the maze, one row per line of input
for (int r=0;r<maxRow;r++) {
line = scanner.nextLine();
char chr;
// For each row, read it in as a sequence of characters, one for each kind of maze element
for (int c = 0;c<maxCol;c++) {
chr = line.charAt(c);
switch (chr) {
// Walls
case '*': cell[r][c] = WALL; break;
// Start symbol
case 'S':
case 's': cell[r][c] = START; break;
// Goal symbol
case 'G':
case 'g': cell[r][c] = GOAL; break;
// Pathways
case ' ': cell[r][c] = 0; break;
// If a number is present, this is used to initialize a cell to have been visited before.
case '0': cell[r][c] = 0; break;
case '1': cell[r][c] = 1; break;
case '2': cell[r][c] = 2; break;
case '3': cell[r][c] = 3; break;
case '4': cell[r][c] = 4; break;
case '5': cell[r][c] = 5; break;
case '6': cell[r][c] = 6; break;
case '7': cell[r][c] = 7; break;
case '8': cell[r][c] = 8; break;
case '9': cell[r][c] = 9; break;
// If it is none of these, it is an error
default:
System.out.println(chr+" is not a valid maze character");
isValidMaze = false;
break;
}
}
}
// If the maze is valid display it, else give an error message and terminate.
if (isValidMaze)
System.out.println(mazeToString());
else {
System.out.println("Error! Since there is an invalid character in the input data, the program stops!");
System.exit(0);
}
// If the path to the file does not result in a valid file, given a good error message
} catch (Exception e) {
System.out.println("Error! The file <" + dataPath + "> cannot be found!");
System.exit(0);
}
}
/*****
* This is the mainline. It performs the bulk of the work and calls supporting methods from
* above to help it do the work.
*
* @param args The program parameters are ignored.
*/
public static void main(String[] args) {
System.out.println("Exercise04");
// Read in the maze from the fixed filename stored in the constant dataPath and display it.
readTheMaze();
// Ask the user to specify a location in the maze in order to analyze which direction
// the maze runner should go if it finds itself at that location.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a row and column number for the maze runner!");
// As long as the user inputs something other than an empty line, the program will loop.
String inputLine = keyboard.nextLine().trim();
while (inputLine.length() > 0) {
// Read in the user's response in terms of a row and column number
Scanner inputScanner = new Scanner(inputLine);
currentRow = inputScanner.nextInt();
currentCol = inputScanner.nextInt();
// Check to see if the numbers are valid
if (currentRow < 1 || currentRow > maxRow-2 )
System.out.println("Error! The row number must be in the range 1 through "+ maxRow + "; it was: " + currentRow);
else if (currentCol < 1 || currentCol > maxCol-2)
System.out.println("Error! The column number must be in the range 1 through "+ maxCol + "; it was: " + currentCol);
else if (cell[currentRow][currentCol] == -1)
System.out.println("Error! You have specified the location of a wall. The maze runner can never get here.");
else if (cell[currentRow][currentCol] == WALL)
System.out.println("Error! You have specified the location of a wall. The maze runner can never get here.");
else if (cell[currentRow][currentCol] == START)
System.out.println("Error! You have specified the location of the start symbol. The maze runner can never get here.");
else if (cell[currentRow][currentCol] == GOAL)
System.out.println("Error! You have specified the location of the goal. The maze runner can never get here.");
else {
// The row and column numbers are valid
// Display the portion of the maze of interest before the move
System.out.println(mazeToString(currentRow-1, currentRow+1, currentCol-1, currentCol+1));
// Compute the next move and return true if the maze runner moves; false if at the goal or not move is possible
System.out.println("\nThe Maze Runner has moved: " + makeMove() + ".");
// Display the current position of the maze runner
System.out.println("The new location is row: " + currentRow +"; column: " + currentCol + "\n");
// Display the new context of the maze of interest after the move
System.out.println(mazeToString(currentRow-1, currentRow+1, currentCol-1, currentCol+1));
}
System.out.println("------------------------------");
System.out.println(mazeToString());
System.out.println("Enter a row and column number for the maze runner!");
inputLine = keyboard.nextLine().trim();
}
System.out.println("------------------------------");
System.out.println("The program ends!");
}
}
La actividad fue exitosa y se logró resolver, la ejecución mostró el resultado esperado.
Las líneas donde centramos la resolución del problema fueron las siguientes:
public static boolean makeMove(){
if(getContents(0,1)==GOAL||getContents(-1,0)==GOAL||
getContents(1,0) ==GOAL || getContents(0,-1) == GOAL)return false;
if(notWall(1,0)){
if(getMarks(1,0)<=getMarks(-1,0)&&getMarks(1,0)<=getMarks(0,1)&&
getMarks(1,0)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
}
if(notWall(0,1)){
if(getMarks(1,0)<=getMarks(-1,0)&&getMarks(0,1)<=getMarks(0,1)&&
getMarks(0,1)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
}
if(notWall(-1,0)){
if(getMarks(-1,0)<=getMarks(-1,0)&&getMarks(-1,0)<=getMarks(0,1)&&
getMarks(-1,0)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
}
if(notWall(0,-1)){
if(getMarks(0,-1)<=getMarks(-1,0)&&getMarks(0,-1)<=getMarks(0,1)&&
getMarks(0,-1)<=getMarks(0,-1)){
if(cell[currentRow][currentCol]>=0)cell[currentRow][currentCol]++;
return true;
}
//System.out.println("The makeMove method was called.");
}
return false;
}
En el código podemos revisar que mediante el condicional if, se verifica si esa coordenada ya fue pasada por el maze runner y le agrega un número 1, en caso de que sea la segunda ocasión que pasa, se cambia el valor que muestra la celda por el número 2 o por el número 3, según sea el caso.
Tuesday, September 23rd, 2014
SDP03 Exercise 03
By: Eduardo Zavala Ramírez
We solved the exercise 03 of the iCarnegie course. It was not necessary either to use a computer nor a write a only code line. The fact is that the objective of the exercise was to practice algorithms to solve a maze applying some rules to move the point. The most important rules were that if the object goes a place ahead or backwards, it has to leave a mark (footprint) which is really a number to be able to count how many times the maze runner passed over each place.
The document, already solved, looks like this:
DIAGRAMA 1: UN LABERINTO
+------------G--+--+
| | |
| +--+ +-+------++ |
| | | | |
| |
| | ++ | | +---+ | |
| | ++ | | | | | |
| | | | | | | | |
| +--+-+ | +-+ | | |
| | |
| | | |
| +- | + +-----+ | |
| | |
| |
+--- | | +-----+ | |
| | | |
| | |
| +- | | | ----+ | |
| | | | |
| |
| +--+ | | ------+ |
| | |
| |
+------+ +-------+ |
| |
+S-----------------+
En el siguiente espacio, escriba los pasos de cada uno
de los procedimientos probados.
Ejemplo:
1. Entrar al laberinto avanzando a la celda de arriba
2. Girar a la derecha, avanzar 18 celdas
3. Girar hacia arriba y avanzar 5 celdas
4. <continuar describiendo la trayectoria>
Por cada procedimiento, integrar la figura del
laberinto en la que se muestren los valores de las marcas de tiza.
Para hacer las pruebas, puede imprimir el formato que
he preparado con una mejor y clara representación de las celdas, paredes y
posiciones de la entrada y la meta.
Resultados
Procedimiento 1:
1. …↑
2. …→
3. …←
4. …↓
Procedimiento 2:
1. …←
2. …↑
3. …→
4. …↓
Procedimiento 3:
1. …→
2. …↑
3. …↓
4. …←
We designed the structure of directions to solve the maze, we also tested them and we found the second procedure like the most efficient set of steps to solve it.
