Académique Documents
Professionnel Documents
Culture Documents
SISTEMAS DE INFORMACION
Objetivos
1. enseñar a los alumnos a analizar , diseñar y programar para aplicacion con
archivos inicialmente y base de datos despues
ANALIZAR. identificar los problema o sub problemas
Diseñar , como van eer las entradas , salidas variables, constantes, se usa arreglos ,
punteros , programación visual. Pseudocodigo,diagrmas de flujo etc
Programar . una vez definida la lógica de solución ( que se puede resolver de mucha
maneras
conocimientos de programación en visual Basic versiones 2005 hasta 2019 tanto en
modo consola como en modo formulario
Conocimiento de entrada y salidas , sentencias de controles funciones y procedentitos,
estructura de datos como arreglos, registros, cadenas, archivos clases y objetos
Conocimiento de Programación visual en Windows , como formulario controles
Windows form, gráficos , bitmaps, propiedades metodos y eventos, eventos del mouse
y del teclado, manejo de archivos y directorios
opcionalmente , uso de libreias graficas como opengl y otros. control MS chart ,
Interface con Office todo en modo escritorio
en la siguientes practicas será en web y manejo de base de datos
PUNTO X y R1 R2 R3
0 55 120 1 12 -1
1 130 100 0 11 2
2 190 70 1 3 10
3 320 40 2 4 6
4 360 30 3 5 -1
5 400 110 4 6 32
6 345 125 3 7 31
7 300 143 6 30 8
8 255 170 9 7 -1
9 260 183 8 10 -1
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 2 -
10 220 170 2 11 14
11 175 188 1 10 12
12 70 201 0 11 13
13 82 266 12 16 14
14 247 234 15 10 13
15 269 299 14 16 39
16 93 319 13 17 15
17 100 371 16 18 21
18 217 371 17 20 19
19 260 360 39 18 24
20 220 410 18 21 23
21 110 425 17 22 20
22 110 480 21 23 -1
23 240 460 22 20 24
24 310 450 23 25 19
25 340 450 24 26 37
26 340 400 27 25 36
27 330 360 26 28 -1
28 350 320 39 27 29
29 370 310 28 34 30
30 350 260 31 7 29
31 420 250 30 32 -1
32 450 230 33 5 -1
33 470 290 32 38 -1
34 410 300 29 33 -1
35 420 350 36 34 27
36 450 380 37 35 -1
37 460 420 25 38 36
38 500 410 37 33 -1
39 320 320 19 15 28
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 3 -
mifuente
SOLUCION EN Excel
1. leer la matriz que tiene la sigueitne estructura
a
NR
O X1 Y1
0 1 1
1 5 1
2 5 4
3 1 4
La primera columna es la etiqueta del puntos
La segunda columna es la coordenada X
la tercera columna es la coordenada Y
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 4 -
evaluación
presentación del trabajo grupal 5 puntos
funcionamiento individual 5 puntos video de la evidencia autocalificad y revisado por el
delgado o comisión de calificación y por profesor
desarrollo delos ejercicios y guía de practicas y libro de porgrmacion
calificación por delegado o comisión
aportes del alumnos. incluye aporte en el agente viajero. por ejemplo puede ser en
python y blender ( el primer examen podría ser sobre el mismo trabajo
5.
trabajo seleccionados hasta 5 . para escogido para la acreditación y o feria virtual o
física
TAREA
resuelva el problema por el método d easignacion
El elemento cij representa el costo de asignar al trabajador i al puesto j (i,j = 1,2,..., n).
No se pierde generalidad al suponer que la cantidad de trabajadores siempre es igual a
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 5 -
TABLA 5.33
Pinta
Podar r Lavar Minimo renglon
John 15 10 9 p1=9
Keren 9 15 10 p2=9
1
Como en el modelo de transporte, el método húngaro clásico, diseñado principalmente para cálculos a
mano es algo del pasado, y se presenta aquí sólo por razones históricas. Hoy, la necesidad de esos
métodos rápidos de cómputo no es tan apremiante, porque el problema se puede resolver como una
programación lineal normal, usando programas de cómputo muy eficientes.
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 6 -
Terri 10 12 8 p3=8
A continuación se resta el mínimo del renglón de cada renglón respectivo, para obtener
la matriz reducida de la tabla 5.34.
TABLA 5.34
Podar Pintar Lavar
John 6 1 0
Karen 0 6 1
Terri 2 4 0
minimo de la
columna q1=0 q2=1 q3=0
La aplicación del paso 2 produce los mínimos de columna de la tabla 5.34. Al restar
esos valores de las columnas respectivas se obtiene la matriz reducida de la tabla 5.35.
TABLA 5.35
Podar Pintar Lavar
John 6 0 0
Kare
n 0 5 1
Terri 2 3 0
Las celdas con elementos cero subrayados son la solución óptima. Eso quiere decir
que John va a pintar la cochera, Karen podará el pasto y Terri lavará los autos. El costo
total para el señor Klyne será 9 + 10 + 8 = $27. Esta cantidad también será siempre
igual (p1 + p2 + p3) + (q1 + q2 + q3) =(9 + 9 + 8) + (0 + 1 + 0) = $27. En la sección
siguiente se justifica este resultado.
Los pasos presentados para el método húngaro funcionaron bien en el ejemplo
anterior, porque sucede que los elementos cero en la matriz final producen una
asignación factible (en el sentido que las tareas se asignan en forma única a los niños).
En algunos casos los ceros que se producen en los pasos 1 y 2 no producen una
solución factible en forma directa. En este caso se necesitan más pasos para llegar a la
asignación óptima (factible). En el ejemplo que sigue se ilustra este caso.
Nota. Se puede primero asignar las columnas
Ejemplo 5.4-2 Suponga que el caso del ejemplo 5.4-1 se amplía a cuatro hijos y
cuatro tareas. La tabla 5.36 resume los elementos de costo en el problema.
TABLA 5.36
Tarea
1 2 3 4
niñ
1
o 1 4 6 3
2 9 7 10 9
3 4 5 11 7
4 8 7 8 5
La solución óptima, que se indica con los ceros subrayados, dice que se debe asignar
el niño 1 a la tarea 1, el niño 2 a la tarea 3, el niño 3 a la tarea 2 y el niño 4 a la tarea 4.
TABLA 5.39
Tare
a
1 2 3 4
1 0 2 1 1
niño 2 3 0 0 2
3 0 0 3 2
4 4 2 0 0
ce una cota superior más pequeña, o si hay evidencia de que no puede conducir a una
mejor cota superior. El recorrido óptimo se da en el nodo con la menor cota superior.
El siguiente ejemplo proporciona los detalles de los algoritmos de ramificación y
acotamiento, y TSP.
Ejemplo 11.3-1
Considere la siguiente matriz TSP de 5 ciudades:
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 9 -
En el nodo 1 del árbol de ramificación y acotamiento, el subrecorrido más corto 1-3-1 crea
la rama x13 5 0 que conduce al nodo 2 y x31 5 0 que conduce al nodo 3. Los problemas de asignación
asociados en los nodos 2 y 3 se crean a partir del problema en el nodo 1 estableciendo d13
5 q y d31 5 q, respectivamente.
En este momento, podemos examinar el nodo 2 o el nodo 3, y elegir arbitrariamente explorar
el nodo 2. Su solución de asignación es 2-5-2 y 1-4-3-1 con z 5 17. Como la solución no es un
recorrido, seleccionamos el subrecorrido más corto 2-5-2 para ramificación: la rama x25 5 0 conduce
al nodo 4, y la rama x52 5 0 conduce al nodo 5.
Ahora tenemos tres subproblemas sin explorar: los nodos 3, 4, y 5. Examinamos arbitrariamente
el subproblema en el nodo 4, estableciendo d25 5 q en la matriz de distancias en el nodo
2. La solución resultante, el recorrido 1-4-5-2-3-1, produce la cota superior más pequeña z 5 21.
Los dos subproblemas en los nodos 3 y 5 permanecen sin explorar. Seleccionando arbitrariamente
el subproblema 5, establecemos d52 5 q en la matriz de distancias en el nodo 2. El resultado
es el recorrido 1-4-2-5-3-1 con la cota superior más pequeña z 5 19. El subproblema 3 es el
único que permanece sin explorar. Sustituyendo d31 5 q en la matriz de distancias en el nodo 1,
obtenemos una mejor solución de recorrido: 1-3-4-2-5-1 con la cota superior más pequeña z 5 16.
Se han examinado todos los nodos del árbol, y por consiguiente se completa la búsqueda de
ramificación y acotamiento. El recorrido óptimo es el asociado con la cota superior más pequeña:
1-3-4-2-5-1 de 16 unidades de longitud
Imports System.IO
Imports System.Drawing
Public Class Form1
Dim Pluma As Pen
Dim Grafico As Graphics
Dim brocha As SolidBrush
Dim MiFuente As New Font("Verdana", 12, FontStyle.Bold)
Sub MostrarCuadricula(A(,) As String, nf As Integer, nc As Integer)
Dim fila, col As Integer
DataGridView1.ColumnCount = nc
DataGridView1.RowCount = nf
For col = 0 To nc - 1
DataGridView1.Columns(col).Width = 40
DataGridView1.Columns(col).HeaderText = A(0, col)
Next
For fila = 0 To nf - 1
DataGridView1.Rows(fila).HeaderCell.Value = Str(fila)
For col = 0 To nc - 1
DataGridView1.Rows(fila).Cells(col).Value = A(fila + 1, col)
Select Case A(fila + 1, col)
Case 0 : DataGridView1.Rows(fila).Cells(col).Style.BackColor =
Color.Red
Case 1 : DataGridView1.Rows(fila).Cells(col).Style.BackColor =
Color.Green
Case Else : DataGridView1.Rows(fila).Cells(col).Style.BackColor =
Color.White
End Select
Next
Next
End Sub
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 11 -
ini = CadLista(fila)
fin = CadLista(fila + 1)
x1 = MPuntos(ini, 1)
y1 = MPuntos(ini, 2)
x2 = MPuntos(fin, 1)
y2 = MPuntos(fin, 2)
Pluma.Color = Color.Lime
Pluma.Width = 3
Pluma.Color = Color.Red
Grafico.DrawLine(Pluma, cx + x1 * Ex, cy + y1 * Ey, cx + x2 * Ex, cy + y2 *
Ey)
Next
Pluma.Color = Color.Blue
End Sub
Sub graficarTodas(Masig(,) As String, nasig As Integer)
Dim fila As Integer
Dim x1, y1, x2, y2 As Single
For fila = 0 To nasig - 1
For col = 0 To nasig - 1
If Masig(fila, col) = 1 Then
x1 = MPuntos(fila, 1)
y1 = MPuntos(fila, 2)
x2 = MPuntos(col, 1)
y2 = MPuntos(col, 2)
Grafico.DrawLine(Pluma, Cx + x1 * Ex, Cy + y1 * Ey, Cx + x2 * Ex, Cy
+ y2 * Ey)
End If
Next
Next
End Sub
Private Sub BtnCalRuta_Click(sender As Object, e As EventArgs) Handles
btnCalcularRuta.Click
Cadruta = txtRuta.Text
Cadruta = Replace(Cadruta, ";", "")
dist1 = CadDistancia(Cadruta)
ListBox1.Items.Add("cadruta " & Cadruta & " dist " & dist1)
GraficarPuntos(MPuntos, nf)
Coordenadas()
MnuGrafAsignadas_Click(sender, e)
MnuGraficarRuta_Click(sender, e)
txtDist.Text = dist1
End Sub
'MostrarVector(VS, nf - 1)
ListBox1.Items.Add("resultado")
nelem = nf - 1
Dim cad1 As String = ""
dist1 = G(X, VS, nelem, cad1)
Cadruta = "0-" & cad1
ListBox1.Items.Add(" ruta menor " & Cadruta & "dist " & dist1)
txtDist.Text = dist1
txtRuta.Text = Cadruta
'MnuGrafAsignadas_Click(sender, e)
MnuGraficarRuta_Click(sender, e)
'MnuGraficarPuntos_Click(sender, e)
txtTiempo.Text = Now
'ListBox1.Items.Add(Now)
End Sub
End Sub
End Class
Imports System.IO
Module Module1
Sub main()
Imports System.IO
Module Module2
Sub CrearMatrizAsigTotal(Masig(,) As String, nf As Integer, nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If fila = col Then
Masig(fila, col) = 0
Else
Masig(fila, col) = 1
End If
Next
Next
End Sub
Function ContarLetra(Cadena As String, letra As Char)
Dim LARGO As Integer = Len(Cadena)
Dim cont, cant As Integer
For cont = 0 To LARGO - 1
If Cadena(cont) = letra Then
cant = cant + 1
End If
Next
Return cant
End Function
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As String, ByRef nf As
Integer, ByRef nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
nc = ContarLetra(cadena, vbTab) + 1
Do While Not (cadena = "")
cadena = cadena & vbTab
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = subcadena
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
srLector.Close()
End Sub
Randomize()
For fila = 0 To nf - 1
A(fila, 0) = fila
A(fila, 1) = Int(Rnd() * LimMax)
A(fila, 2) = Int(Rnd() * LimMay)
'A(fila, 3) = 1
Next
End Sub
End Module
Imports System.IO
Module Module3
Public X As Integer = 1
'Public ArchivoRel As String = "C:\datos1\ArchivoRelaciones.txt"
Public Const Maxfilas As Integer = 200
Public Const Maxcol As Integer = 200
'Public MAR(Maxfilas, Maxcol) As String
Public cont As Integer
Public VS(Maxfilas) As Integer
Public nelem As Integer
Public rutamenor As String
Public archivo As StreamWriter
Public ArchivoSalida As String = "C:\datos1\DatosSalida.txt"
Public ls As Integer = 4 ' limite superior para el recursivo
Public li As Integer = 0
Public ArchivoPuntos As String = "C:\datos1\Puntos.txt"
Public ArchivoDistancias As String = "C:\datos1\Distancias.txt"
Public ArchivoAsignacion As String = "C:\datos1\Asignacion.txt"
Public dist1 As Single = 0
Public menor As Single = 9999
Public maxval As Integer = 9999
Public MD(Maxfilas, Maxcol) As String
Public MPuntos(Maxfilas, 4) As String
Public Masig(Maxfilas, Maxfilas) As String
Public MasigT(Maxfilas, Maxfilas) As String
Public nf As Integer
Public nc As Integer = 3
Public ALto As Integer = 500
Public Ancho As Integer = 600
Public Cadruta As String
Public Cx As Integer = 10
Public Cy As Integer = ALto
Public Ex As Single = 5 ' poner 5 para aleatorio
Public Ey As Single = -5 ' poner -5 para aleagtorio
Public LimMax As Integer = 100
Public LimMay As Integer = 100
End Module
Module Module4
Sub VectorMenor(Vs() As Integer, Vcopia() As Integer, nro As Integer, ByRef ne As
Integer)
Dim col, cont As Integer
cont = 0
For col = 0 To ne - 1
If Vs(col) = nro Then Continue For
Vcopia(cont) = Vs(col)
cont = cont + 1
Next
ne = cont
End Sub
Sub GenerarVector(VA() As Integer, ne As Integer)
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 18 -
Function G(X As Integer, VS() As Integer, largo As Integer, ByRef cad1 As String) As
Single
Dim col, nro, ne As Integer
Dim f As Single
Dim cadmenor As String = ""
Dim menor As Single = maxval
If largo = 1 Then
nro = VS(0)
f = Val(MD(X, nro)) + Val(MD(nro, 0))
If f < menor Then
menor = f
cadmenor = nro & "-" & X
End If
rutamenor = cadmenor
Else
Dim cadruta1 As String = ""
Dim Vcopia(Maxfilas) As Integer
For col = 0 To largo - 1
nro = VS(col)
ne = largo
VectorMenor(VS, Vcopia, nro, ne)
f = MD(X, nro) + G(nro, Vcopia, ne, cad1)
cad1 = cad1 & "-" & X
If f < menor Then
menor = f
cadruta1 = cad1
End If
Next
cadmenor = cadruta1
End If
rutamenor = cadmenor
cad1 = rutamenor
Return menor
End Function
End Module
Imports System.IO
Imports System.Drawing
Public Class Form1
Dim Pluma As Pen
Dim Grafico As Graphics
Dim brocha As SolidBrush
Dim MiFuente As New Font("Verdana", 10, FontStyle.Bold)
Sub MostrarVectorFormulario(VA() As Integer, nc As Integer)
Dim col As Integer
Dim Cadena As String = ""
For col = 0 To nc - 1
Cadena = Cadena & VA(col) & vbTab
Next
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 21 -
ListBox1.Items.Add(Cadena)
End Sub
Sub MostrarMatrizFormulario(A(,) As Single, nf As Integer, nc As Integer)
Dim fila, col As Integer
Dim Cadena, cad1 As String
For fila = 0 To nf - 1
Cadena = ""
For col = 0 To nc - 1
cad1 = A(fila, col)
Cadena = Cadena & A(fila, col) & vbTab
Next
ListBox1.Items.Add(Cadena)
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PictureBox1.Width = Ancho
PictureBox1.Height = ALto + 20
Grafico = PictureBox1.CreateGraphics
Pluma = New Pen(Color.Blue, 2)
brocha = New SolidBrush(Color.FromArgb(255, 255, 0))
End Sub
Sub Coordenadas()
Grafico.DrawLine(Pluma, 0, Cy, Ancho, Cy)
Grafico.DrawLine(Pluma, Cx, 0, Cx, ALto)
End Sub
Sub GraficarPuntos(Mpuntos(,) As Single, nfPuntos As Integer)
Dim fila As Integer
Dim x1, y1, ancho1, alto1 As Single
ancho1 = Ex / 10
alto1 = Math.Abs(Ey / 10)
For fila = 0 To nfPuntos - 1
x1 = Mpuntos(fila, 1)
y1 = Mpuntos(fila, 2)
Grafico.DrawRectangle(Pluma, Cx + x1 * Ex, Cy + y1 * Ey, ancho1, alto1)
Grafico.DrawString(fila, MiFuente, brocha, Cx + x1 * Ex, Cy + y1 * Ey)
Next
End Sub
Sub GraficarRuta(CadRuta As String, cx As Integer, cy As Integer)
Dim fila, ini, fin As Integer
Dim CadLista() As String = Split(CadRuta, "-")
Dim tam As Integer = UBound(CadLista)
Dim x1, y1, x2, y2 As Single
For fila = 0 To tam - 1
ini = CadLista(fila)
fin = CadLista(fila + 1)
x1 = MPuntos(ini, 1)
y1 = MPuntos(ini, 2)
x2 = MPuntos(fin, 1)
y2 = MPuntos(fin, 2)
Pluma.Color = Color.Lime
Pluma.Width = 3
Pluma.Color = Color.Red
Grafico.DrawLine(Pluma, cx + x1 * Ex, cy + y1 * Ey, cx + x2 * Ex, cy + y2 *
Ey)
Next
Pluma.Color = Color.Blue
End Sub
Sub graficarTodas(Masig(,) As Integer, nasig As Integer)
Pluma.Width = 1
Pluma.Color = Color.Lime
Dim fila As Integer
Dim x1, y1, x2, y2 As Single
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 22 -
txtNpuntos.Text = nf
txtDist.Text = dist1
GraficarPuntos(MPuntos, nf)
Coordenadas()
graficarTodas(MAsigT, nf)
GraficarRuta(Cadruta, Cx, Cy)
End Sub
Private Sub btnGraficarPuntos_Click(sender As Object, e As EventArgs) Handles
btnGraficarPuntos.Click
GraficarPuntos(MPuntos, nf)
Coordenadas()
End Sub
Private Sub btnTodas_Click(sender As Object, e As EventArgs) Handles btnTodas.Click
graficarTodas(MAsigT, nf)
End Sub
Private Sub btnRuta_Click(sender As Object, e As EventArgs) Handles btnRuta.Click
GraficarRuta(Cadruta, Cx, Cy)
End Sub
Private Sub btnAleatorio_Click(sender As Object, e As EventArgs) Handles
btnAleatorio.Click
ListBox1.Items.Clear()
Grafico.Clear(Color.Black)
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 23 -
nf = txtNpuntos.Text
nc = 4
GenerarPuntosAleatorios(MPuntos, nf)
ListBox1.Items.Add("Matriz de Puntos XY Z generados aleatoriamente")
MostrarMatrizFormulario(MPuntos, nf, nc)
ObtenerMatrizDistancias(MPuntos, MD, nf, nf)
ListBox1.Items.Add("Matriz de Distancias ")
MostrarMatrizFormulario(MD, nf, nf)
CrearMatrizAsigTotal(MAsigT, nf, nf)
txtNpuntos.Text = nf
GraficarPuntos(MPuntos, nf)
'Coordenadas()
'graficarTodas(MAsigT, nf)
End Sub
Private Sub FuerzaBruta(sender As Object, e As EventArgs) Handles
btnFuerzaBruta.Click
Me.Text = "FUERZA BRUTA"
btnBorrar_Click(sender, e)
Dim cad As String = ""
menor = maxval
Cadruta = "vacio"
generarCombi(0, nf - 1, cad)
ListBox1.Items.Add(" cad ruta " & Cadruta & " dist " & menor)
dist1 = menor
GraficarPuntos(MPuntos, nf)
Coordenadas()
graficarTodas(MAsigT, nf)
GraficarRuta(Cadruta, Cx, Cy)
txtRuta.Text = Cadruta
txtDist.Text = dist1
End Sub
Private Sub GrabarPuntosAleatorios(sender As Object, e As EventArgs) Handles
btnGrabaraleatorio.Click
GrabarMatriz(ArchivoSalida, MPuntos, nf, nc)
End Sub
Private Sub btnBorrar_Click(sender As Object, e As EventArgs) Handles btnBorrar.Click
Grafico.Clear(Color.Black)
ListBox1.Items.Clear()
End Sub
End Sub
'End Sub
End Class
Module Module1
Sub MetodoInsercion()
GenerarVector(Vr2q, nf)
nv2 = nf
nv1 = 3
MostrarVector(Vr2q, nv2)
GenerarVectorInicial(Vr1, nf, nc)
dist1 = DistRutaVector(Vr1, nv1)
'Console.WriteLine("vector vr1 dist " & dist1)
'MostrarVector(Vr1, nv1)
Console.WriteLine("vector vr1 dist " & dist1)
MostrarVector(Vr1, nv1)
EliminarVector(Vr2q, Vr1(0), nv2)
EliminarVector(Vr2q, Vr1(1), nv2)
EliminarVector(Vr2q, Vr1(2), nv2)
Console.WriteLine("Vector Generado Vr2q ")
MostrarVector(Vr2q, nv2)
ProcesoInsercion(Vr1, dist1)
Console.WriteLine("RESULTADOS distancia " & dist1)
MostrarVector(Vr1, nv1)
End Sub
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 25 -
Sub Main()
RecuperarMatriz(ArchivoPuntos, MPuntos, nf, nc)
MostrarMatriz(MPuntos, nf, nc)
'RecuperarMatriz(ArchivoDistancias, MD, nf, nf)
ObtenerMatrizDistancias(MPuntos, MD, nf, nf)
Console.WriteLine("matriz de Distancias")
MostrarMatriz(MD, nf, nf)
'GrabarMatriz(ArchivoSalida, MD, nf, nf)
CrearMatrizAsigTotal(MAsigT, nf, nf)
Console.ReadLine()
End Sub
End Module
Imports System.IO
Module MODULE2
Function DistRutaVector(VA() As Integer, ne As Integer) As Single
Dim col, ini, fin As Integer
Dim suma As Single = 0
For col = 0 To ne - 2
ini = VA(col)
fin = VA(col + 1)
suma = suma + Val(MD(ini, fin))
Next
suma = suma + Val(MD(fin, VA(0)))
Return suma
End Function
Sub InsertarVector(V() As Integer, nro As Integer, lugar As Integer, ByRef ne As
Integer)
Dim col As Integer
For col = ne To lugar + 1 Step -1
V(col) = V(col - 1)
Next
V(lugar) = nro
ne = ne + 1
End Sub
Sub ProcesoFuerzaBruta()
Dim cad As String = ""
menor = maxval
Cadruta = "vacio"
generarCombi(0, nf - 1, cad)
dist1 = menor
Console.WriteLine(" cad ruta " & Cadruta & " dist " & dist1)
End Sub
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 26 -
Imports System.IO
Module Module3
Public Vr1(Maxfilas) As Integer
Public Vr1w(Maxfilas) As Integer ' vector de trabajo
Public Vr2q(Maxfilas) As Integer
Module Module4
Sub CrearMatrizAsigTotal(Mt(,) As Integer, nf As Integer, nc As Integer)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If fila = col Then
Mt(fila, col) = 0
Else
Mt(fila, col) = 1
End If
Next
Next
End Sub
Function SumaProducto(MD(,) As Single, MAsig(,) As Integer, nf As Integer, nc As
Integer) As Single
Dim fila, col As Integer
Dim suma As Single = 0
For fila = 0 To nf - 1
For col = 0 To nc - 1
suma = suma + MD(fila, col) * MAsig(fila, col)
Next
Next
Return suma
End Function
Function CadDistancia(Cadruta As String) As Single
Dim col, ini, fin As Integer
Dim Vcad() As String = Split(Cadruta, "-")
Dim dist1 As Single
For col = 0 To UBound(Vcad) - 1
ini = Vcad(col)
fin = Vcad(col + 1)
dist1 = dist1 + Val(MD(ini, fin))
Next
Return dist1
End Function
Sub GenerarPuntosAleatorios(A(,) As Single, nf As Integer)
Dim fila As Integer
Randomize()
For fila = 0 To nf - 1
A(fila, 0) = fila
A(fila, 1) = Int(Rnd() * LimMax)
A(fila, 2) = Int(Rnd() * LimMay)
A(fila, 3) = 1
Next
End Sub
Sub GenerarVectorInicial(Vr1() As Integer, nf As Integer, nc As Integer)
Dim v1, v2, v3, v1a, v2a, v3a As Integer
Dim dist2 As Single = 0
Dim Menor2 As Single = 9999
For v1 = 0 To nf - 3
For v2 = v1 + 1 To nf - 2
For v3 = v2 + 1 To nf - 1
dist2 = Val(MD(v1, v2)) + Val(MD(v2, v3)) + Val(MD(v3, v1))
'Console.WriteLine(v1 & vbTab & v2 & vbTab & v3 & vbTab & dist2)
If dist2 < Menor2 Then
Menor2 = dist2
v1a = v1
v2a = v2
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 29 -
v3a = v3
End If
Next
Next
Next
Vr1(0) = v1a
Vr1(1) = v2a
Vr1(2) = v3a
End Sub
Sub GenerarVector(VA() As Integer, nf As Integer)
Dim col As Integer
For col = 0 To nf - 1
VA(col) = col
Next
End Sub
Sub ProcesoInsercion(Vr1() As Integer, ByRef ctotal As Single)
Dim nro, fila As Integer
Cadruta = "nulo"
Dim Menor1 As Single = 9999
Dim lugana, NroGana As Integer
Do
Menor1 = 9999
For fila = 0 To nv1
For col = 0 To nv2 - 1
CopiarVector(Vr1, Vr1w, nv1)
nro = Vr2q(col)
nv1w = nv1
InsertarVector(Vr1w, nro, fila, nv1w)
dist1 = DistRutaVector(Vr1w, nv1w)
If dist1 < Menor1 Then
Menor1 = dist1
lugana = fila
NroGana = nro
End If
Next
Next
'Console.WriteLine("Lug gana " & vbTab & lugana & " NroGana " & vbTab &
NroGana & vbTab & Menor1 & vbTab)
InsertarVector(Vr1, NroGana, lugana, nv1)
EliminarVector(Vr2q, NroGana, nv2)
Loop While nv2 > 0
ctotal = Menor1
End Sub
Sub EliminarVector(V() As Integer, nro As Integer, ByRef Ne As Integer)
Dim col, lugar As Integer
For col = 0 To Ne - 1
If V(col) = nro Then
lugar = col
Exit For
End If
Next
For col = lugar To Ne - 1
V(col) = V(col + 1)
Next
Ne = Ne - 1
End Sub
' y1 = mp(fila, 1)
' x1 = mp(fila, 2)
' For col = 0 To nc - 1
' y2 = mp(col, 1)
' x2 = mp(col, 2)
' dist = distancia(x1, y1, x2, y2)
' If fila = col Then
' MD(fila, col) = maxval
' Else
' MD(fila, col) = dist
' End If
' Next
' Next
'End Sub
'Function distancia(x1 As Single, y1 As Single, x2 As Single, y2 As Single) As Single
' Return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))
'End Function
Function DistCadena(cadruta As String) As Single
Dim Vruta() As String = Split(cadruta, "-")
Dim fila, ini, fin As Integer
Dim dist As Single = 0
For fila = 0 To UBound(Vruta) - 1
ini = Vruta(fila)
fin = Vruta(fila + 1)
dist = dist + Val(MD(ini, fin))
Next
Return dist
End Function
Sub generarCombi(li As Integer, ls As Integer, cad As String)
Dim fila, pos As Integer
Dim cad1 As String = cad
For fila = 0 To ls
pos = InStr(cad1, fila)
If pos = 0 Then
cad1 = cad & fila & "-"
If li < ls Then
generarCombi(li + 1, ls, cad1)
Else
cad1 = cad1 & cad1(0)
dist1 = DistCadena(cad1) ' quitar MD despues para mayor velocidad
'Console.WriteLine(cad1 & " " & dist1)
If dist1 < menor Then
Cadruta = cad1
menor = dist1
End If
End If
End If
Next
End Sub
End Module
Imports System.IO
Module Module5
Function BuscarColumna(Masig(,) As Integer, nc As Integer, Nrofila As Integer) As
Integer
Dim col As Integer
For col = 0 To nc - 1
If Masig(Nrofila, col) = 1 Then
Return col
End If
Next
Return -1
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 31 -
End Function
Function buscar(Masig(,) As Integer, nf As Integer, nc As Integer, ByRef y1 As
Integer, ByRef x1 As Integer) As Integer
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
If Masig(fila, col) = 1 Then
y1 = fila
x1 = col
Return 1
End If
Next
Next
Return -1
End Function
Function GenerarCadenas(Masig(,) As Integer, nf As Integer, nc As Integer) As String
Dim r1, y1, x1, ini, fin As Integer
Dim cadena, subcadena As String
cadena = ""
Do
r1 = buscar(Masig, nf, nc, y1, x1)
If r1 = -1 Then
Exit Do
End If
ini = y1
subcadena = ini
Do
fin = BuscarColumna(Masig, nc, ini)
If fin = -1 Then
Exit Do
End If
subcadena = subcadena & "-" & fin
Masig(ini, fin) = 0
ini = fin
Loop
cadena = cadena & subcadena & ";"
Loop
Return cadena
End Function
Function Probarruta(cad As String) As Integer
Dim vCad() As String = Split(cad, ";")
Dim tam As Integer = UBound(vCad)
Return tam
End Function
Sub ObtenerMatrizDistancias(mp(,) As Single, MD(,) As Single, nf As Integer, nc As
Integer)
Dim fila, col As Integer
Dim dist, x1, y1, x2, y2 As Single
For fila = 0 To nf - 1
y1 = mp(fila, 1)
x1 = mp(fila, 2)
For col = 0 To nc - 1
y2 = mp(col, 1)
x2 = mp(col, 2)
dist = distancia(x1, y1, x2, y2)
If fila = col Then
MD(fila, col) = maxval
Else
MD(fila, col) = dist
End If
Next
Next
Sistemas de Informacion Tarea 1 / 2. Solución de problema del Agente viajero\Ismael Veliz Vilca - 32 -
End Sub
Function distancia(x1 As Single, y1 As Single, x2 As Single, y2 As Single) As Single
Return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))
End Function
Function SumaProducto(MD(,) As Single, MAsig(,) As Integer, nf As Integer, nc As
Integer) As Single
Dim fila, col As Integer
Dim suma As Single = 0
For fila = 0 To nf - 1
For col = 0 To nc - 1
suma = suma + MD(fila, col) * MAsig(fila, col)
Next
Next
Return suma
End Function
Sub IniciarMatriz(A(,) As Integer, nf As Integer, nc As Integer, letra As String)
Dim fila, col As Integer
For fila = 0 To nf - 1
For col = 0 To nc - 1
A(fila, col) = letra
Next
Next
End Sub
End Module