Browse Source

Actualizando con README de google docs e imagenes. Anadi preguntas diagnosticas.

Rafael Arce Nazario 9 years ago
parent
commit
cdfc370227
3 changed files with 643 additions and 309 deletions
  1. 643
    309
      README.md
  2. BIN
      images/main1.png
  3. BIN
      images/main2.png

+ 643
- 309
README.md View File

@@ -1,309 +1,643 @@
1
-[English](#markdown-header-arrays-of-objects-prmap) | [Español](#markdown-header-arreglos-de-objetos-prmap)
2
-
3
-#Arreglos de Objetos - PRMap
4
-
5
-
6
-
7
-![](http://demo05.cloudimage.io/s/resize/300/i.imgur.com/UnUXImq.png)
8
-![](http://demo05.cloudimage.io/s/resize/350/i.imgur.com/7AneJpf.png)
9
-
10
-
11
-Los arreglos te permiten guardar y trabajar con varios datos del mismo tipo. Los datos se guardan en espacios de memoria consecutivos a los que se puede acceder utilizando el nombre del arreglo e índices o suscritos que indican la posición en que se encuentra el dato. Es fácil acceder a los elementos de un arreglo utilizando ciclos.
12
-
13
-Una tarea bien común en programación usando C++ lo es el trabajar con  arreglos de objetos. En la experiencia de laboratorio de hoy estarás trabajando con datos "georeferenciados" de pueblos en Puerto Rico en donde tendrás atributos como el nombre y la latitud y longitud de su localización que utilizarás para ilustrar propiedades en un mapa.
14
-
15
-##Objetivos:
16
-
17
-1. Crear dinámicamente y manipular un arreglo de objetos.
18
-2. Codificar funciones para procesar arreglos de objetos.
19
-3. Practicar el pasar arreglos de objetos como parámetros de una función.
20
-4. Practicar la lectura secuencial de datos en un archivo.
21
-5. Usar programación modular.
22
-6. Usar estructuras de repetición y control.
23
-
24
-
25
-##Pre-Lab:
26
-
27
-Antes de llegar al laboratorio debes:
28
-
29
-1. haber repasado los conceptos relacionados a arreglos de objetos
30
-2. haber repasado los conceptos relacionados funciones que utilizan arreglos de objetos.
31
-
32
-3. haber repasado como leer datos de un archivo.
33
-
34
-
35
-5. haber estudiado los conceptos e instrucciones de la sesión de laboratorio.
36
-
37
-6. haber tomado el [quiz Pre-Lab 12](http://moodle.ccom.uprrp.edu/mod/quiz/view.php?id=7649) (recuerda que el quiz Pre-Lab puede tener conceptos explicados en las instrucciones del laboratorio).
38
-
39
----
40
----
41
-
42
-##Datos "georeferenciados"
43
-
44
-Trabajar con arreglos de objetos es una tarea bien común en la programación usando C++. Una vez has leido la información de los objetos en un archivo o provenientes de un usuario, debes depender de tus destrezas algorítmicas y conocimiento sobre C++ para invocar los métodos y funciones adecuadas para procesar los datos correctamente.
45
-
46
-En esta experiencia de laboratorio estarás trabajando con datos "georeferenciados" sobre las ciudades en Puerto Rico. El que un dato sea "georeferenciados" quiere decir que el dato tiene una localización física asociada. Típicamente, esta **localización** son coordenadas de longitud y latitud. Por ejemplo, lo que sigue es parte de un archivo que contiene datos georeferenciados de pueblos en Puerto Rico:
47
-
48
-
49
-```
50
-Arroyo 17.9658 -66.0614
51
-Bayamon 18.3833 -66.15
52
-Caguas 18.2342 -66.0486
53
-Dorado 18.4589 -66.2678
54
-Fajardo 18.3258 -65.6525
55
-```
56
-
57
-Como viste en la clase, la manera más común para los programadores en C++ encapsular datos asociados a un ente es utilizando **classes**. Por ejemplo, en el caso de datos georeferenciados, una manera práctica de encapsular la información para cada pueblo sería implementando una clase `GeoreferencedPointOfInterest` que contenga al menos datos (o atributos) para: el nombre del pueblo, su longitud y su latitud. La clase `GOPI` también necesitará implementar métodos para acceder, modificar, y hacer operaciones en sus atributos.
58
-
59
-###La clase `GPOI`
60
-
61
-En esta experiencia de laboratorio te proveemos una clase `GPOI`  con los siguientes métodos de interfase:
62
-
63
-
64
-* `GISPOI()`: constructor por defecto
65
-
66
-* `GISPOI(QString s, double latitude, double longitude)`:  constructor que recibe nombre, longitud y latitud
67
-
68
-* `double getLat()`, `double getLon()`:  "getters" para la latitud y longitud
69
-
70
-* ` QString getName()`:  "getter" para el nombre
71
-
72
-* `void setAll(string s, double a, double b)`: "setter" para todas las propiedades (a la vez) 
73
-
74
-* `double odDistance(const GISPOI &B) const`: dado otro objeto `B` de la clase  `GPOI`, devuelve la distancia *ortodrómica* (*orthodromic*) (la distancia más corta) entre el `GPOI` que invoca y `B`.
75
-
76
-
77
-
78
-##Sesión de laboratorio:
79
-
80
-###Ejercicio 0 - Baja y entiende el código
81
-
82
-**Instrucciones**
83
-
84
-
85
-1. Abre un terminal y escribe el comando `git clone https://bitbucket.org/eip-uprrp/lab12-objecstarrays-prmap.git` para descargar la carpeta `Lab12-ObjectsArrays-prMap` a tu computadora.
86
-
87
-2.  Haz doble "click" en el archivo `prMap.pro` para cargar este proyecto a Qt y correrlo. En su estado actual, el programa solo despliega un mapa de Puerto Rico.
88
-
89
-    Cuando el programa esté terminado necesitará que el usuario entre texto. Por lo tanto, debemos especificar en `Qt Creator` que este programa debe correr en un **terminal**, no en la ventana `QtCreator`. Para hacer esto, marca el botón de `Projects` en la parte de la izquierda de la ventana de `QtCreator`. Luego selecciona `Run` en la pestaña cerca de la parte de arriba de la ventana. Asegúrate de que la caja `Run in terminal` esté seleccionada.
90
-
91
-3. Haz "Build" del programa para que determines si quedan **errores**. Quizás ves algunas advertencias ("warnings") debido a que hay algunas funciones que estean incompletas. Estarás completando estas funciones durante el laboratorio.
92
-
93
-4. Abre el archivo `main.cpp`. En este archivo es que estarás escribiendo tu código. El archivo contiene las siguientes funciones:
94
- 
95
-    1. `void printArrayOfCities(GISPOI A[], int size)`: Dado un arreglo `A` de objetos de la clase `GISPOI` y su tamaño, imprime todos los pueblos en el arreglo. Puedes usar esta función como parte de tu proceso de depuración ("debugging").
96
-    
97
-    
98
-    2. `int countLinesInFile(ifstream &file)`: Dada una referencia a un objeto que representa un archivo, esta función cuenta y devuelve el número de filas del archivo.
99
-
100
-    3. `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)`: Dado el objeto `ifstream` de un archivo, un arreglo de pueblos, y el número de registros para leer de un archivo, esta función lee los valores de un archivo y llena el arreglo con objetos. **Esta es una función que tú implementarás**.
101
-
102
-    4. `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)` : Dado un arreglo `A` de pueblos, determina los dos pueblos que quedan más lejos. La función devuelve (por referencia) los índices de estas ciudades en el arreglo. **Esta es una función que tú implementarás**.
103
-
104
-    5. `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`: Dado un arreglo `A` de pueblos, determina los dos pueblos que quedan más cerca. La función devuelve (por referencia) los índices de estas ciudades en el arreglo. **Esta es una función que tú implementarás**.
105
-    
106
-
107
-    6. `double cycleDistance(GISPOI A[], int size, int P[])`: Dado un arreglo `A` de pueblos, el tamaño de este arreglo, y un arreglo `P` con una permutación de los enteros en `[0,size-1]`, computa y devuelve la distancia de viajar el ciclo de pueblos `A[P[0]]` $\rightarrow$ `A[P[1]]` $\rightarrow \cdots \rightarrow$ `A[P[size-1]]`. 
108
-  
109
-        Por ejemplo, si los pueblos que se leen del archivo fueran  Mayaguez, Ponce, Yauco y San Juan (en ese orden) y la permutación `P` es $\left(3, 1, 0, 2\right)$, la función debe computar la distancia del ciclo San Juan $\rightarrow$ Ponce $\rightarrow$ Mayaguez $\rightarrow$ Yauco $\rightarrow$ San Juan.
110
-
111
-        **Esta es una función que tú implementarás**.
112
-
113
-Hay otras dos funciones que debes conocer:
114
-
115
-
116
-1. `void MainWindow::drawLine(const GISPOI &city01, const GISPOI &city02)`: Dada una referencia a dos objetos `GISPOI`, la función pinta una línea entre ellos.
117
-
118
-2. `void drawPoints(GISPOI* gisLocations, unsigned int size);`: Dado un arreglo de objetos `GISPOI` y su tamaño, despliega sus localizaciones como puntos en el mapa.
119
-
120
-### Ejercicio 1 - lee los puntos georeferenciados a un arreglo 
121
-
122
-Recuerda que solo estarás cambiando código en el archivo `main.cpp`. Tu primera tarea será añadir código para leer todo el contenido de un archivo a un arreglo de objetos `GISPOI`.
123
-
124
-
125
-1. En la función `main()`, añade las instrucciones necesarias para abrir el archivo que contiene la información del pueblo georeferenciado. El archivo está en el directorio `data` y es `pr10.txt`. Necesitas dar el `path` completo del archivo como parámetro del método `open()` de tu objeto `ifstream`. Como siempre, cuando uses archivos debes verificar si el nombre del archivo que pusiste se puede abrir para leer exitosamente.
126
-
127
-2. Invoca la función `int countLinesInFile(ifstream &inFile)` para obtener el número de líneas en el archivo. Puedes imprimir el número de líneas obtenido de modo que valides que tu programa está funcionando correctamente.
128
-
129
-3. Crea un arreglo **dinámicamente** tan grande como el número de líneas en tu programa.
130
-
131
-4. Modifica la función `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)` de modo que lea todas las líneas en el archivo a objetos en el arreglo.
132
-
133
-5. En la función `main()`, invoca la función `readFileToArray`, pasando la referencia al archivo, el arreglo que creaste en el paso 3, y su tamaño.
134
-
135
-6. Luego de invocar la función `readFileToArray` puedes invocar la función `void printArrayOfCities(GISPOI A[], int size)` para imprimir los nombres y georeferencias de los puntos leidos del archivo.
136
-
137
-7. Pídele al usuario el nombre del archivo de texto que contiene los datos con el siguiente formato: CityName Latitude Longitude. Algunos ejemplos de archivos son:  `cities.txt`, `calif.txt`, y `pr.txt`. 
138
-
139
-8. Invoca el método `drawPoints(GISPOI* gisLocations, unsigned int size)` en el objeto `w` de modo que se muestre un punto en el mapa para cada pueblo. La invocación debe hacerse de esta manera: `w.drawPoints(A, size)` (*asumiendo que `A` es el nombre de tu arreglo*). Debes obtener algo parecido a la siguiente figura:
140
-
141
-    ![](http://demo05.cloudimage.io/s/resize/400/i.imgur.com/7AneJpf.png) 
142
-
143
-
144
-### Ejercicio 2 - las funciones max y min 
145
-
146
-Una vez que tengas la información de los pueblos georeferenciados en el arreglo de objetos, puedes comenzar a procesarlos de muchas formas interesantes. Comenzaremos con algunas operaciones básicas.
147
-
148
-1. Lee la documentación e implementa la la función `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoca la función desde `main()`.
149
-
150
-2. Usa el método `void drawLine(const GISPOI &city01, const GISPOI &city02)` del objeto `w` para dibujar una línea que conecte los pueblos más lejanos. Nota que el segundo y tercer parámetro de este método son **referencias a los objetos que representan los pueblos** (no sus índices en el arreglo).
151
-
152
-3. Lee la documentación e implementa la función `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoca la función desde `main()`.
153
-
154
-4. Usa el método `void drawLine(const GISPOI &city01, const GISPOI &city02)` del objeto `w` para dibujar una línea que conecte los pueblos más cercanos.
155
-
156
-
157
-### Ejercicio 3 - computa la distancia del ciclo
158
-
159
-1. Lee la documentación e implementa la función `double cycleDistance(GISPOI A[], int size, int P[])`. Invoca la función desde `main()` como se indica en los comentarios dentro de la función `main()`:
160
-
161
-    1. Primero con $P = \left(0, 2, 4, 6, 8, 1, 3, 5, 7, 9\right)$,
162
-    2. luego con = \left(0, 3, 6, 9, 1, 4, 7, 2, 5, 8\right)$. 
163
-
164
-
165
-### Ejercicio 3 - ¡más diversión!
166
-
167
-Cambia tu código de modo que ahora abra el archivo `pr.txt`. Valida tus resultados y ¡maravíllate de tu gran logro!
168
-
169
-## Entregas:
170
-
171
-1. Entrega el archivo `main.cpp` utilizando este [enlace a Moodle](http://moodle.ccom.uprrp.edu/mod/assignment/view.php?id=7650).  Recuerda comentar adecuadamente las funciones, usar indentación adecuada y buenas prácticas para darle nombre a las variables.
172
-
173
-----------
174
-
175
-[English](#markdown-header-arrays-of-objects-prmap) | [Español](#markdown-header-arreglos-de-objetos-prmap)
176
-
177
-#Arrays of Objects - PRMap
178
-
179
-
180
-### Objectives
181
-Throughout this exercise the students will practice:
182
-
183
-* reading a text file sequentially 
184
-* repetition and control structures
185
-* creating and manipulating an array of objects
186
-* writing functions to process arrays of objects
187
-* passing arrays of objects as parameters
188
-* modular programming
189
-
190
-### Concepts
191
-
192
-Working with arrays of objects is a very common task in C++ programs. Once you have read information about the objects from a file and/or the user, you must relly on your algorithmic and C++ skills to invoke the proper methods and functions in order to correctly process the data.
193
-
194
-In this lab, we will be working with *georeferenced* data about the cities in Puerto Rico.  When a data is georeferenced* it simply means that it has an associated location in pyhsical space. Typically this **location** means latitude and longitude coordinates.  For example, the following is part of file that contains georeferenced data for some Puertorrican cities:
195
-
196
-
197
-```
198
-Arroyo 17.9658 -66.0614
199
-Bayamon 18.3833 -66.15
200
-Caguas 18.2342 -66.0486
201
-Dorado 18.4589 -66.2678
202
-Fajardo 18.3258 -65.6525
203
-```
204
-
205
-As you saw in class, **classes** are the most common way that C++ programmers encapsulate data that is associated to an entity. For example, in the case of the georeferenced points, a practical way to encapsulate the information about each city would be to implement a **GeoreferencedPointOfInterest** class that contains at least data members for: the name of the city, its latitude and longitude.  The **GPOI** class would also need to implement methods to access, modify, and perform computations on its properties. 
206
-
207
-### The GPOI class
208
-
209
-In this lab, you are provided a **GPOI** class with the following interface:
210
-
211
-* `GISPOI()`: the default constructor
212
-
213
-* `GISPOI(QString s, double latitude, double longitude)`:  constructor that accepts name, longitude and latitude.
214
-
215
-* `double getLat()`, `double getLon()`:  getters for the latutide, longitude.
216
-
217
-* ` QString getName()`:  getter for the name.
218
-
219
-* `void setAll(string s, double a, double b)`: setter for all the properties (at once)
220
-
221
-* `double odDistance(const GISPOI &B) const`: given B, another GPOI object, returns the *orthodromic* distance (or the closest distance) between the invoking GPOI and B.
222
-
223
-
224
-### Exercise 0 - Download and understand the code
225
-
226
-1. Download _______.
227
-
228
-2. Open the .pro file. Build the program and run it. In its current state, the program simply displays a map of Puerto Rico. This map is provided so that you can viualize the results of your program.
229
-
230
-    When you complete this program, it will need some text input from the user. Thus, we need to specify in *Qt Creator* that we expect this program to run in a **terminal**, i.e. not on the QtCreator window. To do this, please click of the `Projects` button on the left part of the *QtCreator* window. Then choose `Run` on the tab near the top of the window. Then make sure that the checkbox `Run in terminal` is checked.
231
-
232
-3. Build the program just to determine if there are any outstanding **errors**. You may see some warnings which are due to the fact that some of the functions are incomplete (you will complete throughout this lab.)
233
-
234
-3. Open the `main.cpp` file. This is the file where you will be writing your code. This file contains the following functions:
235
-
236
-    1. `void printArrayOfCities(GISPOI A[], int size)`: Given A, an array of GISPOI objects and its size, prints all the cities in the array. You may use this function as part of your debugging.
237
-    
238
-    2. `int countLinesInFile(ifstream &file)`: Given a reference to the object that represents a file, this function counts and returns the number of lines in the file. 
239
-
240
-    3. `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)`: Given the ifstream object of a file, an array of cities and the number of records to read from the file, this function reads the values from the file and populates the array with objects. **THIS IS A FUNCTION THAT YOU WILL IMPLEMENT**
241
-
242
-    4. `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)` : Given A, the array of cities, determines the farthest two cities. Returns (by reference) the indices of the two cities in the array. **THIS IS A FUNCTION THAT YOU WILL IMPLEMENT**
243
-
244
-    5. `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`: Given A, the array of cities, determines the closest two cities. Returns (by reference) the indices of the two cities in the array. **THIS IS A FUNCTION THAT YOU WILL IMPLEMENT**
245
-
246
-    5. `double cycleDistance(GISPOI A[], int size, int P[])`: Given the array of cities, the size of the array and a array (P) with a permutation of the integers [0, size-1] computes and returns the distance to travel the cycle of cities A[P[0]] $\rightarrow$ A[P[1]] $\rightarrow$ .... $\rightarrow$ A[P[size-1]]. 
247
-
248
-        For example, if the cities read from the file where Mayaguez, Ponce, Yauco and San Juan (in that order) and the permutation $P$ is $left\(3, 1, 0, 2\right)$, the function should compute the distance of a cycle from San Juan $\rightarrow$ Ponce $\rightarrow$ Mayaguez $\rightarrow$ Yauco $\rightarrow$ San Juan.
249
-
250
-
251
-        **THIS IS A FUNCTION THAT YOU WILL IMPLEMENT**
252
-
253
-There is one additional function that you need to know:
254
-
255
-1. `void MainWindow::drawLine(const GISPOI &city01, const GISPOI &city02)`: Given (a reference to) two GISPOI objects, paints a line between them.
256
-
257
-2. `void drawPoints(GISPOI* gisLocations, unsigned int size);`: Given an array of GISPOI objects and their size, displays their locations as points in the map.
258
-
259
-### Exercise 1 - read the georeferenced points into an array
260
-
261
-Remember that you will only be changing code in the `main.cpp` file. Your first task will be to add code to read the entire contents of a file into an array of GISPOI objects.
262
-
263
-1. In the main function, add the necessary instructions to open the file that contains the georeferenced city information. The file is `pr10.txt` in the data directory. You need to provide the complete path to the file as a parameter to the `open()`  method of your `ifstream` object. As always, when using files you should verify if the entered name is a file that can be succefully opened for reading.
264
-
265
-2. Invoke the `int countLinesInFile(ifstream &inFile)` function to obtain the number of lines in the file. You may print out the number obtained so that you can validate is your program is working correctly.
266
-
267
-3. **Dynamically** create an array as big as the number of lines in the file.
268
-
269
-3. Modify the `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)` function so that it reads all the lines in the file to the objects in the array. 
270
-
271
-1. In the main function invoke the `readFileToArray` function, passing the reference to the file, the array you created in step ???, and its size.
272
-
273
-1. After invoking `readFileToArray` you may invoke `void printArrayOfCities(GISPOI A[], int size)` to print the names and georeferences of the points read from the file. 
274
-
275
-1. Ask the user for the name of the text file that contains data in the following format: CityName Latitude Longitude. Here are example files: cities.txt, calif.txt, and pr.txt. 
276
-
277
-1. Invoke the method `drawPoints(GISPOI* gisLocations, unsigned int size)` on the `w` object as follows so that a point will be shown in the map for each city: `w.drawPoints(A, size)` (*assuming that A is your array*). You should obtain something similar to the next figure. 
278
-
279
-    ![](http://demo05.cloudimage.io/s/resize/400/i.imgur.com/7AneJpf.png) 
280
-
281
-
282
-
283
-### Exercise 2 - the max and min functions
284
-
285
-Once we have the information of georeferenced cities in an array of objects, we can start processing them in many interesting ways. We will start with some basic operations.
286
-
287
-1. Read the documentation and implement the function `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoke the function from `main()`. 
288
-
289
-1. Use the `void drawLine(const GISPOI &city01, const GISPOI &city02)` method of the `w` object to paint a line connecting the two farthest cities.  Notice that the second and third parameters of this method are ** references to the objects that represent the cities** (not their indices in the array).
290
-
291
-1. Read the documentation and implement the function `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoke the function from `main()`. 
292
-
293
-1. Use the `void drawLine(const GISPOI &city01, const GISPOI &city02)` method of the `w` object to paint a line connecting the two closest cities. 
294
-
295
-
296
-
297
-### Exercise 3 - compute the cycle distance
298
-
299
-1. Read the documentation and implement the function `double cycleDistance(GISPOI A[], int size, int P[])`. Invoke the function from `main()` as indicated in the comments inside the main function:
300
-
301
-    1. First with $P = \left(0, 2, 4, 6, 8, 1, 3, 5, 7, 9\right)$
302
-    2. Then with $P = \left(0, 3, 6, 9, 1, 4, 7, 2, 5, 8\right)$ 
303
-
304
-
305
-### Exercise 4 - more fun
306
-
307
-1. Change your code so that it now opens the `pr.txt` file.  Validate your results and wonder at your great achievement.
308
-
309
-### Deliverables
1
+[English](#markdown-header-arrays-of-objects-prmap) | [Español](#markdown-header-arreglos-de-objetos-prmap)
2
+
3
+
4
+#Arreglos de Objetos - PRMap
5
+
6
+
7
+
8
+
9
+![main1.png](images/main1.png)
10
+![main2.png](images/main2.png)
11
+
12
+
13
+Los arreglos de datos (*arrays*) nos facilitan guardar y trabajar con grupos de datos del mismo tipo. Los datos se guardan en espacios de memoria consecutivos a los que se puede acceder utilizando el nombre del arreglo e índices o suscritos que indican la posición en que se encuentra el dato. Las estructuras de repetición nos proveen una manera simple de acceder a los datos de un arreglo. 
14
+
15
+
16
+Un *objeto* es una entidad que se utiliza en muchos lenguajes de programación para integrar los datos y el código que opera en ellos, haciendo más fácil el modificar programas grandes. Una tarea bien común en programación usando C++ lo es el trabajar con  arreglos de objetos. En la experiencia de laboratorio de hoy estarás trabajando con datos "georeferenciados" de pueblos en Puerto Rico, en donde tendrás atributos, como el nombre del pueblo, la latitud y longitud de su localización, que utilizarás para ilustrar propiedades en un mapa.
17
+
18
+
19
+
20
+
21
+##Objetivos:
22
+
23
+
24
+1. Crear dinámicamente y manipular un arreglo de objetos.
25
+
26
+
27
+2. Codificar funciones para procesar arreglos de objetos.
28
+
29
+
30
+3. Practicar el pasar arreglos de objetos como parámetros de una función.
31
+
32
+
33
+4. Practicar la lectura secuencial de datos en un archivo.
34
+
35
+
36
+5. Usar programación modular.
37
+
38
+
39
+6. Usar estructuras de repetición y control.
40
+
41
+
42
+
43
+
44
+##Pre-Lab:
45
+
46
+
47
+Antes de llegar al laboratorio debes haber:
48
+
49
+
50
+1. Repasado los conceptos relacionados a arreglos de objetos.
51
+
52
+
53
+2. Repasado los conceptos relacionados funciones que utilizan arreglos de objetos.
54
+
55
+
56
+3. Repasado cómo leer datos de un archivo.
57
+
58
+
59
+4. Estudiado los conceptos e instrucciones para la sesión de laboratorio.
60
+
61
+
62
+5. Tomado el quiz Pre-Lab que se encuentra en Moodle.
63
+
64
+
65
+---
66
+
67
+
68
+---
69
+
70
+
71
+
72
+
73
+##Datos "georeferenciados"
74
+
75
+
76
+Trabajar con arreglos de objetos es una tarea bien común en la programación usando C++. Una vez has leido la información de los objetos de un archivo o provenientes de un usuario, debes depender de tus destrezas algorítmicas y conocimiento sobre C++ para invocar los métodos y funciones adecuadas para procesar los datos correctamente.
77
+
78
+
79
+En esta experiencia de laboratorio estarás trabajando con datos "georeferenciados" sobre las ciudades en Puerto Rico. El que un dato sea "georeferenciado" quiere decir que el dato tiene una localización física asociada. Típicamente, esta **localización** son coordenadas de longitud y latitud. Por ejemplo, lo que sigue es parte de un archivo que contiene datos georeferenciados de pueblos en Puerto Rico:
80
+
81
+
82
+---
83
+
84
+
85
+```
86
+Arroyo 17.9658 -66.0614
87
+Bayamon 18.3833 -66.15
88
+Caguas 18.2342 -66.0486
89
+Dorado 18.4589 -66.2678
90
+Fajardo 18.3258 -65.6525
91
+```
92
+
93
+
94
+**Figura 1.** Parte del contenido de una archivo de datos georeferenciados de pueblos en Puerto Rico; contiene nombre del pueblo, coordenadas de latitud y coordenada de longitud.
95
+
96
+
97
+---
98
+
99
+
100
+###Distancia ortodrómica
101
+
102
+
103
+Para calcular la distancia entre dos puntos en el plano Euclideano, trazas el segmento de  línea recta que une a los puntos y calculas su largo utilizando la fórmula de distancia que estudiaste en tu curso de Pre-cálculo. Para calcular la distancia entre dos puntos  en la superficie de una esfera no utilzas el segmento de línea que los une, utilizas la distancia más corta entre esos puntos medida sobre la esfera. Esta distancia se llama *distancia ortodrómica*. Para calcular la distancia ortodrómica entre dos puntos en el globo terráqueo se usan las coordenadas de latitud y longitud.
104
+
105
+
106
+
107
+
108
+###La clase `GPOI`
109
+
110
+
111
+La manera más común para los programadores en C++ encapsular datos asociados a un ente es utilizando **clases**. Por ejemplo, en el caso de datos georeferenciados, una manera práctica de encapsular la información para cada pueblo sería implementando una clase `GeoreferencedPointOfInterest` que contenga al menos datos (o atributos) para: el nombre del pueblo, su latitud y su longitud. La clase `GPOI` también necesitará implementar métodos para acceder, modificar y hacer operaciones en sus atributos.
112
+
113
+
114
+En esta experiencia de laboratorio te proveemos una clase `GPOI`  con los siguientes métodos de interfase:
115
+
116
+
117
+
118
+
119
+* `GISPOI()`: constructor por defecto
120
+
121
+
122
+* `GISPOI(QString s, double latitude, double longitude)`:  constructor que recibe nombre, longitud y latitud
123
+
124
+
125
+* `double getLat()`, `double getLon()`:  "getters" para la latitud y longitud
126
+
127
+
128
+* ` QString getName()`:  "getter" para el nombre
129
+
130
+
131
+* `void setAll(string s, double a, double b)`: "setter" para todas las propiedades (a la vez) 
132
+
133
+
134
+* `double odDistance(const GISPOI &B) const`: dado otro objeto `B` de la clase  `GPOI`, devuelve la distancia *ortodrómica* (*orthodromic*) (la distancia más corta) entre el `GPOI` que invoca y `B`
135
+
136
+
137
+---
138
+
139
+---
140
+
141
+
142
+!INCLUDE "../../eip-diagnostic/PRMap/es/diag-prmap-01.html"
143
+
144
+
145
+!INCLUDE "../../eip-diagnostic/PRMap/es/diag-prmap-02.html"
146
+
147
+
148
+!INCLUDE "../../eip-diagnostic/PRMap/es/diag-prmap-03.html"
149
+
150
+---
151
+
152
+---
153
+
154
+
155
+
156
+
157
+
158
+##Sesión de laboratorio:
159
+
160
+
161
+###Ejercicio 0 - Bajar y entender el código
162
+
163
+
164
+####Instrucciones
165
+
166
+
167
+1. Carga a QtCreator el proyecto `prMap`  haciendo doble "click" en el archivo `prMap.pro` en el directorio `Documents/eip/ObjectsArrays-PRMap` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/objectsarrays-prmap` para descargar la carpeta `ObjectsArrays-PRMap` a tu computadora.
168
+ 
169
+2. Compila y corre el programa. En su estado actual, el programa solo despliega un mapa de Puerto Rico. En este mapa podrás ver los resultados de tu programa. Quizás ves algunas advertencias ("warnings") debido a que hay algunas funciones que están incompletas. Estarás completando estas funciones durante la experiencia de laboratorio.
170
+
171
+
172
+3. Abre el archivo `main.cpp`. En este archivo es que estarás escribiendo tu código. El archivo contiene las siguientes funciones:
173
+ 
174
+    1. `void printArrayOfCities(GISPOI A[], int size)`: Dado un arreglo `A` de objetos de la clase `GISPOI` y su tamaño, imprime todos los pueblos en el arreglo. Puedes usar esta función como parte de tu proceso de depuración ("debugging").
175
+    
176
+    
177
+    2. `int countLinesInFile(ifstream &file)`: Dada una referencia a un objeto que representa un archivo, esta función cuenta y devuelve el número de filas del archivo.
178
+
179
+
180
+    3. `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)`: Dado el objeto `ifstream` de un archivo, un arreglo de pueblos, y el número de registros para leer del archivo, esta función lee los valores del archivo y llena el arreglo con objetos. **Esta es una función que tú implementarás**.
181
+
182
+
183
+    4. `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)` : Dado un arreglo `A` de pueblos, determina los dos pueblos que quedan más lejos. Recuerda que la distancia que calcularás será la distancia *ortodrómica*. La función devuelve (por referencia) los índices de estas ciudades en el arreglo. **Esta es una función que tú implementarás**.
184
+
185
+
186
+    5. `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`: Dado un arreglo `A` de pueblos, determina los dos pueblos que quedan más cerca. Recuerda que la distancia que calcularás será la distancia *ortodrómica*. La función devuelve (por referencia) los índices de estas ciudades en el arreglo. **Esta es una función que tú implementarás**.
187
+    
188
+
189
+
190
+    6. `double cycleDistance(GISPOI A[], int size, int P[])`: Dado un arreglo `A` de pueblos, el tamaño de este arreglo, y un arreglo `P` con una permutación de los enteros en `[0,size-1]`, computa y devuelve la distancia de viajar el ciclo de pueblos `A[P[0]]` $$\rightarrow$$ `A[P[1]]` $$\rightarrow \cdots \rightarrow$$ `A[P[size-1]]`. Recuerda que la distancia que calcularás será la distancia *ortodrómica*.
191
+  
192
+        Por ejemplo, si los pueblos que se leen del archivo fueran  Mayaguez, Ponce, Yauco y San Juan (en ese orden) y la permutación `P` es $$(3, 1, 0, 2$$, la función debe computar la distancia del ciclo San Juan $$\rightarrow$$ Ponce $$\rightarrow$$ Mayaguez $$\rightarrow$$ Yauco $$\rightarrow$$ San Juan.**Esta es una función que tú implementarás**.
193
+
194
+
195
+    Hay otras dos funciones que debes conocer:
196
+
197
+
198
+
199
+
200
+    1. `void MainWindow::drawLine(const GISPOI &city01, const GISPOI &city02)`: Dada una referencia a dos objetos `GISPOI`, la función pinta una línea entre ellos.
201
+
202
+
203
+    2. `void drawPoints(GISPOI* gisLocations, unsigned int size);`: Dado un arreglo de objetos `GISPOI` y su tamaño, despliega sus localizaciones como puntos en el mapa.
204
+
205
+
206
+### Ejercicio 1 - Leer los puntos georeferenciados a un arreglo 
207
+
208
+
209
+Recuerda que solo estarás cambiando código en el archivo `main.cpp`. Tu primera tarea será añadir código para leer todo el contenido de un archivo a un arreglo de objetos `GISPOI`.
210
+
211
+
212
+
213
+
214
+1. En la función `main()`, añade las instrucciones necesarias para abrir el archivo que contiene la información de los pueblos georeferenciados. El archivo que usarás primero está en el directorio `data` y es `pr10.txt`. Necesitas dar el `path` completo del archivo como parámetro del método `open()` de tu objeto `ifstream`. Como siempre, cuando uses archivos debes verificar si el nombre del archivo que pusiste se puede abrir para leer exitosamente.
215
+
216
+
217
+2. Invoca la función `int countLinesInFile(ifstream &inFile)` para obtener el número de líneas en el archivo. Puedes imprimir el número de líneas obtenido de modo que valides que tu programa está funcionando correctamente.
218
+
219
+
220
+3. Crea un arreglo **dinámicamente** tan grande como el número de líneas en tu programa.
221
+
222
+
223
+4. Modifica la función `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)` de modo que lea todas las líneas en el archivo a los objetos en el arreglo.
224
+
225
+
226
+5. En la función `main()`, invoca la función `readFileToArray`, pasando la referencia al archivo, el arreglo que creaste en el paso 3, y su tamaño.
227
+
228
+
229
+6. Luego de invocar la función `readFileToArray` puedes invocar la función `void printArrayOfCities(GISPOI A[], int size)` para imprimir los nombres y georeferencias de los puntos leidos del archivo.
230
+
231
+
232
+7. Invoca el método `drawPoints(GISPOI* gisLocations, unsigned int size)` en el objeto `w` de modo que se muestre un punto en el mapa para cada pueblo. La invocación debe hacerse de esta manera: `w.drawPoints(A, size)` (*asumiendo que `A` es el nombre de tu arreglo*). Debes obtener algo parecido a la siguiente figura:
233
+
234
+
235
+    
236
+
237
+
238
+    ![main1.png](images/main1.png)
239
+
240
+
241
+   
242
+
243
+
244
+
245
+
246
+### Ejercicio 2 - Funciones max y min 
247
+
248
+
249
+Una vez que tengas la información de los pueblos georeferenciados en el arreglo de objetos, puedes comenzar a procesarlos de muchas formas interesantes. Comenzaremos con algunas operaciones básicas.
250
+
251
+
252
+1. Lee la documentación e implementa la la función `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoca la función desde `main()`.
253
+
254
+
255
+2. Usa el método `void drawLine(const GISPOI &city01, const GISPOI &city02)` del objeto `w` para dibujar una línea que conecte los pueblos más lejanos. Nota que el segundo y tercer parámetro de este método son **referencias a los objetos que representan los pueblos** (no sus índices en el arreglo).
256
+
257
+
258
+3. Lee la documentación e implementa la función `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoca la función desde `main()`.
259
+
260
+
261
+4. Usa el método `void drawLine(const GISPOI &city01, const GISPOI &city02)` del objeto `w` para dibujar una línea que conecte los pueblos más cercanos.
262
+
263
+
264
+
265
+
266
+### Ejercicio 3 - Computa la distancia del ciclo
267
+
268
+
269
+1. Lee la documentación e implementa la función `double cycleDistance(GISPOI A[], int size, int P[])`. Invoca la función desde `main()` como se indica en los comentarios dentro de la función `main()`:
270
+
271
+
272
+    1. Primero con $$P =(0, 2, 4, 6, 8, 1, 3, 5, 7, 9)$$,
273
+    2. Luego con = $$P=(0, 3, 6, 9, 1, 4, 7, 2, 5, 8)$$. 
274
+
275
+
276
+
277
+
278
+### Ejercicio 4 - ¡Más diversión!
279
+
280
+
281
+Cambia tu código de modo que ahora abra el archivo `pr.txt`. Valida tus resultados y ¡maravíllate de tu gran logro!
282
+
283
+
284
+
285
+
286
+---
287
+
288
+
289
+---
290
+
291
+
292
+##Entrega
293
+
294
+
295
+Utiliza "Entrega" en Moodle para entregar el archivo `main.cpp`. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.
296
+
297
+
298
+
299
+
300
+
301
+
302
+---
303
+
304
+
305
+---
306
+
307
+
308
+
309
+
310
+## Referencias
311
+
312
+
313
+[1] https://en.wikipedia.org/wiki/Great-circle_distance
314
+
315
+
316
+---
317
+
318
+
319
+---
320
+
321
+
322
+---
323
+
324
+
325
+
326
+
327
+
328
+
329
+[English](#markdown-header-arrays-of-objects-prmap) | [Español](#markdown-header-arreglos-de-objetos-prmap)
330
+
331
+
332
+#Arrays of Objects - PRMap
333
+
334
+
335
+
336
+
337
+![main1.png](images/main1.png)
338
+![main2.png](images/main2.png)
339
+
340
+
341
+
342
+
343
+Arrays help us to store and work with groups of data of the same type. The data is stored in consecutive memory spaces which can be accessed by using the name of the array and indexes or subscripts that indicate the position where the data is stored. Repetition structures provide us a simple way of accessing the data within an array.
344
+
345
+
346
+
347
+
348
+An *object* is an entity that it is used in many programming languages to integrate the data and the code that operates on it, simplifying the modification of large programs. A common task in programming using C++ is working with arrays of objects. In today's laboratory experience you will be working with *georeferenced* data of cities in Puerto Rico, where you will have attributes, such as name of the city, the latitude and longitude of its location, that you will use to illustrate properties in a map.
349
+
350
+
351
+
352
+
353
+##Objectives:
354
+
355
+
356
+1. Dynamically create and manipulate an array of objects.
357
+
358
+
359
+2. Code functions that process arrays of objects.
360
+
361
+
362
+3. Practice passing arrays of objects as parameters in a function.
363
+
364
+
365
+4. Practice the sequential reading of data from a file.
366
+
367
+
368
+5. Use modular programming.
369
+
370
+
371
+6. Use repetition and decision structures.
372
+
373
+
374
+
375
+
376
+##Pre-Lab:
377
+
378
+
379
+Before coming to the laboratory you should have:
380
+
381
+
382
+
383
+
384
+1. Reviewed the concepts related to arrays of objects.
385
+
386
+
387
+2. Reviewed the concepts related to functions that use arrays of objects.
388
+
389
+
390
+3. Reviewed how to read data from a file.
391
+
392
+
393
+4. Studied the concepts and instructions for the laboratory session.
394
+
395
+
396
+5. Taken the Pre-Lab quiz that can be found in Moodle.
397
+
398
+
399
+---
400
+
401
+
402
+---
403
+
404
+
405
+##Georeferenced Data
406
+
407
+
408
+Working with arrays of objects is a very common task in programming with C++. Once you have read the object's information from a file or as user input, you should use your algorithmic skills and knowledge of C++ to invoke the adequate methods and functions to process the data correctly.
409
+
410
+
411
+
412
+
413
+In this laboratory experience, you will be working with *georeferenced* data about the cities in Puerto Rico. When a data is *georeferenced* it simply means that it has an associated location in physical space. Typically this **location** are latitude and longitude coordinates.  For example, the following is part of a file that contains georeferenced data for some Puerto Rican cities:
414
+
415
+
416
+---
417
+
418
+
419
+```
420
+Arroyo 17.9658 -66.0614
421
+Bayamon 18.3833 -66.15
422
+Caguas 18.2342 -66.0486
423
+Dorado 18.4589 -66.2678
424
+Fajardo 18.3258 -65.6525
425
+```
426
+
427
+
428
+**Figure 1.** Part of the content of a file with georeferenced data of cities in Puerto Rico; contains name of the city, coordinates for latitude and longitude.
429
+
430
+
431
+---
432
+
433
+
434
+###Orthodromic Distance
435
+
436
+
437
+To calculate the distance between two points in the Euclidean plane, you trace the straight line segment that joins the points and compute its length using the distance formula you studied in your Pre-Calculus course. To calculate the distance between two points in the surface of a sphere you don't use the straight line segment that joins them, you use the shortest distance between these points measured over the sphere. This distance is called the *orthodromic distance*. To calculate the orthodromic distance between two points in the earth globe, the latitude and longitude coordinates are used.
438
+
439
+
440
+
441
+
442
+###The `GPOI` Class
443
+
444
+
445
+The most common way for C++ programmers to encapsulate data to an entity is by using **classes**. For example, in the case of the georeferenced data, a practical way to encapsulate the information about each city would be to implement a `GeoreferencedPointOfInterest` class that contains at least data members (or attributes) for: the name of the city, its latitude and longitude. The `GPOI` class would also need to implement methods to access, modify, and perform computations on its attributes. 
446
+
447
+
448
+In this laboratory experience, you are provided a `GPOI` class with the following interface methods:
449
+
450
+
451
+* `GISPOI()`: the default constructor
452
+
453
+
454
+* `GISPOI(QString s, double latitude, double longitude)`: constructor that receives name, longitude and latitude.
455
+
456
+
457
+* `double getLat()`, `double getLon()`:  getters for the latitude, longitude.
458
+
459
+
460
+* `QString getName()`:  getter for the name.
461
+
462
+
463
+* `void setAll(string s, double a, double b)`: setter for all the properties (at once)
464
+
465
+
466
+* `double odDistance(const GISPOI &B) const`: given `B`, another `GPOI` object, returns the *orthodromic* distance (or the closest distance) between the invoking `GPOI` and `B`.
467
+
468
+
469
+---
470
+
471
+---
472
+
473
+
474
+
475
+!INCLUDE "../../eip-diagnostic/PRMap/en/diag-prmap-01.html"
476
+
477
+
478
+!INCLUDE "../../eip-diagnostic/PRMap/en/diag-prmap-02.html"
479
+
480
+
481
+!INCLUDE "../../eip-diagnostic/PRMap/en/diag-prmap-03.html"
482
+
483
+---
484
+
485
+---
486
+
487
+##Laboratory Session:
488
+
489
+
490
+### Exercise 0 - Download and understand the code
491
+
492
+
493
+####Instructions
494
+
495
+
496
+1. Load the `prMap` project onto Qt by double clicking on the `prMap.pro` filein the directory `Documents/eip/Arrays-PRMap` of your computer. You may also go to `http://bitbucket.org/eip-uprrp/objectsarrays-prmap` to download the `ObjectsArrays-PRMap` folder to your computer.
497
+
498
+
499
+2. Build and run the program. In its current state, the program simply displays a map of Puerto Rico. This map is provided so that you can visualize the results of your program. You may see some warnings which are due to the fact that some of the functions are incomplete. You will complete them throughout this laboratory experience.
500
+
501
+
502
+3. Open the `main.cpp` file. This is the file where you will be writing your code. This file contains the following functions:
503
+
504
+
505
+    1. `void printArrayOfCities(GISPOI A[], int size)`: Given `A`, an array of `GISPOI` objects and its size, prints all the cities in the array. You may use this function as part of your debugging process.
506
+    
507
+    2. `int countLinesInFile(ifstream &file)`: Given a reference to the object that represents a file, this function counts and returns the number of lines in the file. 
508
+
509
+
510
+    3. `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)`: Given the `ifstream` object of a file, an array of cities and the number of records to read from the file, this function reads the values from the file and populates the array with objects. **This is a function you will implement.**
511
+
512
+
513
+    4. `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)` : Given `A`, an array of cities, determines the farthest two cities. Remember that the distance you will calculate is the *orthodromic* distance. The function returns (by reference) the indices of these cities in the array. **This is a function you will implement.**
514
+
515
+
516
+    5. `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`: Given `A`, an array of cities, determines the closest two cities. Remember that the distance you will compute is the *orthodromic* distance. The function returns (by reference) the indices of these cities in the array. **This is a function you will implement.**
517
+
518
+
519
+    6. `double cycleDistance(GISPOI A[], int size, int P[])`: Given an array of cities `A`, the size of the array, and an array `P` with a permutation of the integers in `[0, size-1]`, computes and returns the distance to travel the cycle of cities `A[P[0]]` $$\rightarrow$$ `A[P[1]]` $$\rightarrow \cdots \rightarrow$$ `A[P[size-1]]`. Remember that the distance you will calculate is the *orthodromic* distance.
520
+
521
+
522
+        For example, if the cities read from the file where Mayaguez, Ponce, Yauco and San Juan (in that order) and the permutation `P` is $$(3, 1, 0, 2$$, the function should compute the distance of a cycle from San Juan $$\rightarrow$$ Ponce $$\rightarrow$$ Mayaguez $$\rightarrow$$ Yauco $$\rightarrow$$ San Juan. **This is a function you will implement.**
523
+
524
+
525
+
526
+
527
+There are two additional functions that you need to know:
528
+
529
+
530
+1. `void MainWindow::drawLine(const GISPOI &city01, const GISPOI &city02)`: Given a reference to two `GISPOI` objects, the function draws a line between them.
531
+
532
+
533
+2. `void drawPoints(GISPOI* gisLocations, unsigned int size);`: Given an array of `GISPOI` objects and their size, displays their locations as points in the map.
534
+
535
+
536
+### Exercise 1 - Read the georeferenced points into an array
537
+
538
+
539
+Remember that you will only be changing code in the `main.cpp` file. Your first task will be to add code to read the entire contents of a file into an array of `GISPOI` objects.
540
+
541
+
542
+1. In the `main()` function, add the necessary instructions to open the file that contains the georeferenced city information. The file that you will use first is `pr10.txt` and it is in the `data` directory. You need to provide the complete `path` to the file as a parameter to the `open()`  method of your `ifstream` object. As always, when using files you should verify if the entered name is a file that can be successfully opened for reading.
543
+
544
+
545
+2. Invoke the `int countLinesInFile(ifstream &inFile)` function to obtain the number of lines in the file. You may print out the number obtained so that you can validate is your program is working correctly.
546
+
547
+
548
+3. **Dynamically** create an array as big as the number of lines in the file.
549
+
550
+
551
+4. Modify the `void readFileToArray(ifstream &file, GISPOI A[], int numOfCities)` function so that it reads all the lines in the file to the objects in the array. 
552
+
553
+
554
+5. In the `main()` function invoke the `readFileToArray` function, passing the reference to the file, the array you created in step 3, and its size.
555
+
556
+
557
+6. After invoking `readFileToArray` you may invoke `void printArrayOfCities(GISPOI A[], int size)` to print the names and georeferences of the points read from the file. 
558
+
559
+
560
+7. Invoke the method `drawPoints(GISPOI* gisLocations, unsigned int size)` on the `w` object so that a point will be shown in the map for each city: `w.drawPoints(A, size)` (*assuming that `A` is the name of your array*). You should obtain something similar to the next figure. 
561
+
562
+
563
+
564
+
565
+  
566
+
567
+
568
+    ![main1.png](images/main1.png)
569
+
570
+
571
+    
572
+
573
+
574
+
575
+
576
+
577
+
578
+### Exercise 2 - Max and min functions
579
+
580
+
581
+Once you have the information of georeferenced cities in the array of objects, you can start processing them in many interesting ways. We will start with some basic operations.
582
+
583
+
584
+1. Read the documentation and implement the function `void maxDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoke the function from `main()`. 
585
+
586
+
587
+2. Use the `void drawLine(const GISPOI &city01, const GISPOI &city02)` method of the `w` object to draw a line connecting the two farthest cities.  Notice that the second and third parameters of this method are ** references to the objects that represent the cities** (not their indices in the array).
588
+
589
+
590
+3. Read the documentation and implement the function `void minDistances(GISPOI A[], int size, int &idxCityA, int &idxCityB)`. Invoke the function from `main()`. 
591
+
592
+
593
+4. Use the `void drawLine(const GISPOI &city01, const GISPOI &city02)` method of the `w` object to draw a line connecting the two closest cities. 
594
+
595
+
596
+
597
+
598
+
599
+
600
+### Exercise 3 - Compute the cycle distance
601
+
602
+
603
+1. Read the documentation and implement the function `double cycleDistance(GISPOI A[], int size, int P[])`. Invoke the function from `main()` as indicated in the comments inside the `main()`   function:
604
+
605
+
606
+    1. First with $$P = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)$$
607
+    2. Then with $$P =(0, 3, 6, 9, 1, 4, 7, 2, 5, 8)$$
608
+
609
+
610
+
611
+
612
+### Exercise 4 - More fun!
613
+
614
+
615
+1. Change your code so that it now opens the `pr.txt` file.  Validate your results and wonder at your great achievement!
616
+
617
+
618
+
619
+
620
+---
621
+
622
+
623
+---
624
+
625
+
626
+##Deliverables
627
+
628
+
629
+Use "Deliverables" in Moodle to hand in the `main.cpp` file. Remember to use good programming techniques, include the name of the programmers involved, and document your program.
630
+
631
+
632
+
633
+
634
+---
635
+
636
+
637
+---
638
+
639
+
640
+## Referencias
641
+
642
+
643
+[1] https://en.wikipedia.org/wiki/Great-circle_distance

BIN
images/main1.png View File


BIN
images/main2.png View File