1
0
This commit is contained in:
2025-10-10 02:12:44 +02:00
commit dac3abf431
212 changed files with 475579 additions and 0 deletions

25
PI4/.classpath Normal file
View File

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry combineaccessrules="false" kind="src" path="/ParteComun">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/Solve">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="/Geneticos">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>

17
PI4/.project Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PI4</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,15 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=20
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=20
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=enabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=20

View File

@@ -0,0 +1,9 @@
// HUERTOS
H0: metrosdisponibles=4;
H1: metrosdisponibles=6;
// VARIEDADES
V0 -> metrosrequeridos=2; incomp=V2,V4,V3;
V1 -> metrosrequeridos=4; incomp=V2,V4;
V2 -> metrosrequeridos=3; incomp=V0,V1,V4;
V3 -> metrosrequeridos=1; incomp=V0,V4;
V4 -> metrosrequeridos=6; incomp=V0,V1,V2,V3;

View File

@@ -0,0 +1,11 @@
// HUERTOS
H0: metrosdisponibles=3;
H1: metrosdisponibles=4;
H2: metrosdisponibles=5;
// VARIEDADES
V0 -> metrosrequeridos=4; incomp=V3,V1,V4;
V1 -> metrosrequeridos=2; incomp=V0,V3,V5;
V2 -> metrosrequeridos=3; incomp=V5,V3;
V3 -> metrosrequeridos=1; incomp=V0,V1,V2,V4;
V4 -> metrosrequeridos=6; incomp=V0,V5,V3;
V5 -> metrosrequeridos=2; incomp=V1,V2,V4;

View File

@@ -0,0 +1,15 @@
// HUERTOS
H0: metrosdisponibles=10;
H1: metrosdisponibles=5;
H2: metrosdisponibles=2;
H3: metrosdisponibles=8;
// VARIEDADES
V0 -> metrosrequeridos=6; incomp=V1,V2,V3,V4,V6;
V1 -> metrosrequeridos=4; incomp=V8,V6,V5,V0,V2,V4,V7;
V2 -> metrosrequeridos=3; incomp=V0,V1,V6,V7,V3,V5,V8;
V3 -> metrosrequeridos=1; incomp=V6,V0,V7,V2,V4,V5;
V4 -> metrosrequeridos=6; incomp=V0,V6,V1,V3,V8;
V5 -> metrosrequeridos=5; incomp=V3,V2,V1,V6,V8;
V6 -> metrosrequeridos=2; incomp=V0,V8,V5,V3,V1,V2,V4,V7;
V7 -> metrosrequeridos=5; incomp=V8,V1,V6,V2,V3;
V8 -> metrosrequeridos=2; incomp=V4,V2,V5,V1,V7,V6;

View File

@@ -0,0 +1,7 @@
Presupuesto = 150
//Id_prod:Precio:Categoria:Valoracion
0:10:0:5
1:150:0:4
2:150:1:4
3:100:2:2
4:120:2:5

View File

@@ -0,0 +1,9 @@
Presupuesto = 100
//Id_prod:Precio:Categoria:Valoracion
0:75:3:5
1:10:2:4
2:15:1:2
3:50:0:2
4:80:1:5
5:95:2:5
6:25:3:4

View File

@@ -0,0 +1,12 @@
Presupuesto = 10
//Id_prod:Precio:Categoria:Valoracion
0:5:0:2
1:4:2:1
2:3:1:3
3:5:3:1
4:5:2:1
5:8:4:1
6:8:1:2
7:7:0:5
8:6:2:4
9:10:1:4

View File

@@ -0,0 +1,9 @@
// DESTINOS
D0: demandaminima=6;
D1: demandaminima=3;
D2: demandaminima=8;
D3: demandaminima=10;
D4: demandaminima=5;
// PRODUCTOS Id_producto -> unidades=integer;coste_almacenamiento=(destino:coste)
P0 -> uds=5; coste_almacenamiento=(0:1),(1:50),(2:10),(3:15),(4:10);
P1 -> uds=100; coste_almacenamiento=(0:4),(1:3),(2:3),(3:2),(4:1);

View File

@@ -0,0 +1,12 @@
// DESTINOS
D0: demandaminima=1;
D1: demandaminima=3;
D2: demandaminima=2;
D3: demandaminima=6;
D4: demandaminima=4;
D5: demandaminima=8;
D6: demandaminima=2;
// PRODUCTOS Id_producto -> unidades=integer;coste_almacenamiento=(destino:coste)
P0 -> uds=6; coste_almacenamiento=(0:1),(1:1),(2:80),(3:50),(4:10),(5:8),(6:1);
P1 -> uds=12; coste_almacenamiento=(0:25),(1:3),(2:1),(3:1),(4:1),(5:5),(6:20);
P2 -> uds=8; coste_almacenamiento=(0:10),(1:3),(2:8),(3:25),(4:15),(5:1),(6:3);

View File

@@ -0,0 +1,15 @@
// DESTINOS
D0: demandaminima=3;
D1: demandaminima=1;
D2: demandaminima=8;
D3: demandaminima=5;
D4: demandaminima=1;
D5: demandaminima=3;
D6: demandaminima=1;
D7: demandaminima=10;
D8: demandaminima=2;
D9: demandaminima=6;
// PRODUCTOS Id_producto -> unidades=integer;coste_almacenamiento=(destino:coste)
P0 -> uds=12; coste_almacenamiento=(0:1),(1:7),(2:1),(3:1),(4:10),(5:8),(6:15),(7:9),(8:1),(9:1);
P1 -> uds=15; coste_almacenamiento=(0:25),(1:3),(2:8),(3:1),(4:1),(5:1),(6:1),(7:1),(8:11),(9:1);
P2 -> uds=13; coste_almacenamiento=(0:1),(1:1),(2:1),(3:25),(4:15),(5:1),(6:30),(7:10),(8:7),(9:1);

View File

@@ -0,0 +1,7 @@
// PERSONAS
P0 -> edad=5; idiomas=(esp),(por); nacionalidad=esp; afinidades=(1:1),(2:5),(3:1),(4:0),(5:1);
P1 -> edad=100; idiomas=(esp),(fra); nacionalidad=fra; afinidades=(0:1),(2:0),(3:5),(4:1),(5:2);
P2 -> edad=9; idiomas=(esp),(ing); nacionalidad=eeuu; afinidades=(0:5),(1:0),(3:1),(4:0),(5:5);
P3 -> edad=99; idiomas=(esp),(ale); nacionalidad=esp; afinidades=(0:1),(1:5),(2:1),(4:2),(5:2);
P4 -> edad=75; idiomas=(esp),(por),(fra),(ale); nacionalidad=ale; afinidades=(0:0),(1:1),(2:0),(3:2),(5:5);
P5 -> edad=78; idiomas=(fra),(ale); nacionalidad=fra; afinidades=(0:1),(1:2),(2:5),(3:2),(4:5);

View File

@@ -0,0 +1,9 @@
// PERSONAS
P0 -> edad=5; idiomas=(esp),(por); nacionalidad=esp; afinidades=(1:5),(2:5),(3:5),(4:5),(5:5),(6:5),(7:1);
P1 -> edad=100; idiomas=(esp),(fra); nacionalidad=fra; afinidades=(0:5),(2:5),(3:5),(4:0),(5:5),(6:0),(7:5);
P2 -> edad=9; idiomas=(ing),(esp); nacionalidad=ing; afinidades=(0:5),(1:5),(3:5),(4:0),(5:5),(6:0),(7:5);
P3 -> edad=99; idiomas=(esp),(ing); nacionalidad=esp; afinidades=(0:5),(1:5),(2:5),(4:5),(5:5),(6:1),(7:0);
P4 -> edad=8; idiomas=(esp); nacionalidad=esp; afinidades=(0:5),(1:0),(2:0),(3:5),(5:5),(6:5),(7:5);
P5 -> edad=6; idiomas=(por); nacionalidad=por; afinidades=(0:5),(1:5),(2:5),(3:5),(4:5),(6:5),(7:5);
P6 -> edad=97; idiomas=(ing),(esp); nacionalidad=ing; afinidades=(0:5),(1:0),(2:0),(3:1),(4:5),(5:5),(7:5);
P7 -> edad=98; idiomas=(fra); nacionalidad=esp; afinidades=(0:1),(1:5),(2:5),(3:0),(4:5),(5:5),(6:5);

View File

@@ -0,0 +1,10 @@
// PERSONAS
P0 -> edad=6; idiomas=(fra),(por); nacionalidad=fra; afinidades=(1:1),(2:5),(3:1),(4:5),(5:5),(6:5),(7:1),(8:1);
P1 -> edad=33; idiomas=(esp),(fra); nacionalidad=fra; afinidades=(0:1),(2:0),(3:5),(4:0),(5:5),(6:0),(7:5),(8:1);
P2 -> edad=9; idiomas=(ing); nacionalidad=ing; afinidades=(0:5),(1:0),(3:1),(4:5),(5:5),(6:0),(7:5),(8:1);
P3 -> edad=33; idiomas=(esp),(ing); nacionalidad=esp; afinidades=(0:1),(1:5),(2:1),(4:1),(5:5),(6:1),(7:0),(8:5);
P4 -> edad=8; idiomas=(esp),(ing); nacionalidad=esp; afinidades=(0:5),(1:0),(2:5),(3:1),(5:5),(6:5),(7:5),(8:1);
P5 -> edad=4; idiomas=(por); nacionalidad=por; afinidades=(0:5),(1:5),(2:5),(3:5),(4:5),(6:5),(7:5),(8:1);
P6 -> edad=33; idiomas=(ing),(esp); nacionalidad=ing; afinidades=(0:5),(1:0),(2:0),(3:1),(4:5),(5:5),(7:5),(8:1);
P7 -> edad=33; idiomas=(fra), (esp); nacionalidad=esp; afinidades=(0:1),(1:5),(2:5),(3:0),(4:5),(5:5),(6:5),(8:1);
P8 -> edad=33; idiomas=(ale), (ing); nacionalidad=ale; afinidades=(0:1),(1:1),(2:1),(3:5),(4:1),(5:1),(6:1),(7:1);

23
PI4/modelos/ej1.lsi Normal file
View File

@@ -0,0 +1,23 @@
head section
Integer getN()
Integer getM()
Integer getMetrosRequeridos(Integer i)
Integer getMetrosDisponibles(Integer j)
Integer incompatible(Integer i, Integer k)
Integer n = getN()
Integer m = getM()
goal section
max sum(x[i,j], i in 0 .. n, j in 0 .. m)
constraints section
sum(x[i,j], j in 0 .. m) <= 1, i in 0 .. n
sum(getMetrosRequeridos(i) x[i,j], i in 0 .. n) <= getMetrosDisponibles(j), j in 0 .. m
x[i,j] + x[k,j] <= 1, i in 0 .. n, k in 0 .. n, j in 0 .. m | incompatible(i,k) = 1
bin
x[i,j], i in 0 .. n, j in 0 .. m

BIN
PI4/modelos/ej1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

21
PI4/modelos/ej2.lsi Normal file
View File

@@ -0,0 +1,21 @@
head section
Integer getN()
Integer getM()
Integer getPrecio(Integer i)
Integer getValoracion(Integer i)
Integer getPresupuesto()
Integer tieneCategoria(Integer i, Integer j)
Integer n = getN()
Integer m = getM()
goal section
min sum(getPrecio(i) x[i], i in 0 .. n)
constraints section
sum(tieneCategoria(i,j) x[i], i in 0 .. n) >= 1, j in 0 .. m
sum(getValoracion(i) x[i], i in 0 .. n) - sum(3 x[i], i in 0 .. n) > 0
sum(getPrecio(i) x[i], i in 0 .. n | tieneCategoria(i,j) > 0) <= getPresupuesto(), j in 0 .. m
bin
x[i], i in 0 .. n

BIN
PI4/modelos/ej2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

18
PI4/modelos/ej3.lsi Normal file
View File

@@ -0,0 +1,18 @@
head section
Integer getN()
Integer getM()
Integer getCantidad(Integer i)
Integer getDemanda(Integer j)
Integer getCoste(Integer i, Integer j)
Integer n = getN()
Integer m = getM()
goal section
min sum(getCoste(i,j) x[i,j], i in 0 .. n, j in 0 .. m)
constraints section
sum(x[i,j], i in 0 .. n) >= getDemanda(j), j in 0 .. m
sum(x[i,j], j in 0 .. m) <= getCantidad(i), i in 0 .. n
int
x[i,j], i in 0 .. n, j in 0 .. m

BIN
PI4/modelos/ej3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

54
PI4/modelos/gurobi/ej1.lp Normal file
View File

@@ -0,0 +1,54 @@
Maximize
x_0_0 + x_0_1 + x_1_0 + x_1_1 + x_2_0 + x_2_1 + x_3_0 + x_3_1 + x_4_0 + x_4_1
Subject To
a0: x_0_0 + x_0_1 <= 1
a1: x_1_0 + x_1_1 <= 1
a2: x_2_0 + x_2_1 <= 1
a3: x_3_0 + x_3_1 <= 1
a4: x_4_0 + x_4_1 <= 1
b0: 2 x_0_0 + 4 x_1_0 + 3 x_2_0 + 1 x_3_0 + 6 x_4_0 <= 4
b1: 2 x_0_1 + 4 x_1_1 + 3 x_2_1 + 1 x_3_1 + 6 x_4_1 <= 6
c0: x_0_0 + x_2_0 <= 1
c1: x_0_1 + x_2_1 <= 1
c2: x_0_0 + x_3_0 <= 1
c3: x_0_1 + x_3_1 <= 1
c4: x_0_0 + x_4_0 <= 1
c5: x_0_1 + x_4_1 <= 1
c6: x_1_0 + x_2_0 <= 1
c7: x_1_1 + x_2_1 <= 1
c8: x_1_0 + x_4_0 <= 1
c9: x_1_1 + x_4_1 <= 1
c10: x_2_0 + x_0_0 <= 1
c11: x_2_1 + x_0_1 <= 1
c12: x_2_0 + x_1_0 <= 1
c13: x_2_1 + x_1_1 <= 1
c14: x_2_0 + x_4_0 <= 1
c15: x_2_1 + x_4_1 <= 1
c16: x_3_0 + x_0_0 <= 1
c17: x_3_1 + x_0_1 <= 1
c18: x_3_0 + x_4_0 <= 1
c19: x_3_1 + x_4_1 <= 1
c20: x_4_0 + x_0_0 <= 1
c21: x_4_1 + x_0_1 <= 1
c22: x_4_0 + x_1_0 <= 1
c23: x_4_1 + x_1_1 <= 1
c24: x_4_0 + x_2_0 <= 1
c25: x_4_1 + x_2_1 <= 1
c26: x_4_0 + x_3_0 <= 1
c27: x_4_1 + x_3_1 <= 1
Binary
x_0_0 x_0_1 x_1_0 x_1_1 x_2_0 x_2_1 x_3_0 x_3_1 x_4_0 x_4_1
End

22
PI4/modelos/gurobi/ej2.lp Normal file
View File

@@ -0,0 +1,22 @@
Minimize
5 x_0 + 4 x_1 + 3 x_2 + 5 x_3 + 5 x_4 + 8 x_5 + 8 x_6 + 7 x_7 + 6 x_8 + 10 x_9
Subject To
a0: 1 x_0 + 0 x_1 + 0 x_2 + 0 x_3 + 0 x_4 + 0 x_5 + 0 x_6 + 1 x_7 + 0 x_8 + 0 x_9 >= 1
a1: 0 x_0 + 0 x_1 + 1 x_2 + 0 x_3 + 0 x_4 + 0 x_5 + 1 x_6 + 0 x_7 + 0 x_8 + 1 x_9 >= 1
a2: 0 x_0 + 1 x_1 + 0 x_2 + 0 x_3 + 1 x_4 + 0 x_5 + 0 x_6 + 0 x_7 + 1 x_8 + 0 x_9 >= 1
a3: 0 x_0 + 0 x_1 + 0 x_2 + 1 x_3 + 0 x_4 + 0 x_5 + 0 x_6 + 0 x_7 + 0 x_8 + 0 x_9 >= 1
a4: 0 x_0 + 0 x_1 + 0 x_2 + 0 x_3 + 0 x_4 + 1 x_5 + 0 x_6 + 0 x_7 + 0 x_8 + 0 x_9 >= 1
b0: 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 >= 3
c0: 8 x_5 <= 10
End

32
PI4/modelos/gurobi/ej3.lp Normal file
View File

@@ -0,0 +1,32 @@
Minimize
1 x_0_0 + 7 x_0_1 + 1 x_0_2 + 1 x_0_3 + 10 x_0_4 + 8 x_0_5 + 15 x_0_6 + 9 x_0_7 + 1 x_0_8 + 1 x_0_9 + 25 x_1_0 + 3 x_1_1 + 8 x_1_2 + 1 x_1_3 + 1 x_1_4 + 1 x_1_5 + 1 x_1_6 + 1 x_1_7 + 11 x_1_8 + 1 x_1_9 + 1 x_2_0 + 1 x_2_1 + 1 x_2_2 + 25 x_2_3 + 15 x_2_4 + 1 x_2_5 + 30 x_2_6 + 10 x_2_7 + 7 x_2_8 + 1 x_2_9
Subject To
a0: x_0_0 + x_1_0 + x_2_0 >= 3
a1: x_0_1 + x_1_1 + x_2_1 >= 1
a2: x_0_2 + x_1_2 + x_2_2 >= 8
a3: x_0_3 + x_1_3 + x_2_3 >= 5
a4: x_0_4 + x_1_4 + x_2_4 >= 1
a5: x_0_5 + x_1_5 + x_2_5 >= 3
a6: x_0_6 + x_1_6 + x_2_6 >= 1
a7: x_0_7 + x_1_7 + x_2_7 >= 10
a8: x_0_8 + x_1_8 + x_2_8 >= 2
a9: x_0_9 + x_1_9 + x_2_9 >= 6
b0: x_0_0 + x_0_1 + x_0_2 + x_0_3 + x_0_4 + x_0_5 + x_0_6 + x_0_7 + x_0_8 + x_0_9 <= 12
b1: x_1_0 + x_1_1 + x_1_2 + x_1_3 + x_1_4 + x_1_5 + x_1_6 + x_1_7 + x_1_8 + x_1_9 <= 15
b2: x_2_0 + x_2_1 + x_2_2 + x_2_3 + x_2_4 + x_2_5 + x_2_6 + x_2_7 + x_2_8 + x_2_9 <= 13
General
x_0_0 x_0_1 x_0_2 x_0_3 x_0_4 x_0_5 x_0_6 x_0_7 x_0_8 x_0_9 x_1_0 x_1_1 x_1_2 x_1_3 x_1_4 x_1_5 x_1_6 x_1_7 x_1_8 x_1_9 x_2_0 x_2_1 x_2_2 x_2_3 x_2_4 x_2_5 x_2_6 x_2_7 x_2_8 x_2_9
End

View File

@@ -0,0 +1,41 @@
package adda.ej1;
import java.util.Locale;
import adda.ej1.common.InRangeVerdurasAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestHuertosAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.10;
AlgoritmoAG.CROSSOVER_RATE = 0.95;
AlgoritmoAG.MUTATION_RATE = 0.8;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType =
StoppingConditionFactory.StoppingConditionType.GenerationCount;
InRangeVerdurasAG p = new InRangeVerdurasAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej1/Ejercicio1DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej1/Ejercicio1DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej1/Ejercicio1DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,30 @@
package adda.ej1;
import java.io.IOException;
import java.util.Locale;
import adda.ej1.common.DatosHuertos;
import adda.util.Titles;
import us.lsi.gurobi.GurobiLp;
import us.lsi.gurobi.GurobiSolution;
import us.lsi.solve.AuxGrammar;
public class TestHuertosPLE {
public static void model(String fichero) throws IOException {
DatosHuertos.iniDatos(fichero);
AuxGrammar.generate(DatosHuertos.class, "modelos/ej1.lsi", "modelos/gurobi/ej1.lp");
Locale.setDefault(Locale.of("en", "US"));
GurobiSolution solution = GurobiLp.gurobi("modelos/gurobi/ej1.lp");
System.out.println(solution.toString());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.of("en", "US"));
System.out.println(Titles.F1);
model("ficheros/ej1/Ejercicio1DatosEntrada1.txt");
System.out.println(Titles.F2);
model("ficheros/ej1/Ejercicio1DatosEntrada2.txt");
System.out.println(Titles.F3);
model("ficheros/ej1/Ejercicio1DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,90 @@
package adda.ej1.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosHuertos {
public static int N;
public static int M;
private static List<Verdura> verduras;
private static List<Huerto> huertos;
public static record Huerto(String nombre, Integer metrosDisponibles) {
public static Huerto of(String s) {
s = s.replace(";", "");
String[] partes = s.split(": metrosdisponibles=");
return new Huerto(partes[0], Integer.valueOf(partes[1]));
}
}
public static record Verdura(String nombre, Integer metrosRequeridos, List<String> incompatibles) {
public static Verdura of(String s) {
s = s.replace(" -> metrosrequeridos=", ";").replace(" incomp=", "");
String[] partes = s.split(";");
return new Verdura(partes[0], Integer.valueOf(partes[1]), Arrays.asList(partes[2].split(",")));
}
}
public static void toConsole() {
String2.toConsole(huertos, "Huertos de verdura:");
String2.toConsole(verduras, "Verduras:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
Integer aux = lineas.indexOf("// VARIEDADES");
List<String> h = lineas.subList(1, aux);
List<String> v = lineas.subList(aux + 1, lineas.size());
huertos = new ArrayList<>();
for(String huerto : h) {
huertos.add(Huerto.of(huerto));
}
verduras = new ArrayList<>();
for(String verdura : v) {
verduras.add(Verdura.of(verdura));
}
N = verduras.size();
M = huertos.size();
// toConsole();
}
public static Verdura getVerdura(Integer i) {
return verduras.get(i);
}
public static Huerto getHuerto(Integer j) {
return huertos.get(j);
}
public static Integer getN() {
return N;
}
public static Integer getM() {
return M;
}
public static Integer getMetrosRequeridos(Integer i) {
return verduras.get(i).metrosRequeridos();
}
public static Integer getMetrosDisponibles(Integer j) {
return huertos.get(j).metrosDisponibles();
}
public static Integer incompatible(Integer i, Integer k) {
return verduras.get(i).incompatibles().contains(verduras.get(k).nombre()) ? 1 : 0;
}
public static void main(String[] args) {
iniDatos("ficheros/ej1/Ejercicio1DatosEntrada1.txt");
}
}

View File

@@ -0,0 +1,98 @@
package adda.ej1.common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import adda.ej1.common.DatosHuertos.Huerto;
import adda.ej1.common.DatosHuertos.Verdura;
import us.lsi.ag.ValuesInRangeData;
import us.lsi.ag.agchromosomes.ChromosomeFactory.ChromosomeType;
public class InRangeVerdurasAG implements ValuesInRangeData<Integer, SolucionHuertos>{
public InRangeVerdurasAG(String fichero) {
DatosHuertos.iniDatos(fichero);
}
@Override
public Integer size() {
// TODO Auto-generated method stub
return DatosHuertos.getN();
}
@Override
public ChromosomeType type() {
// TODO Auto-generated method stub
return ChromosomeType.Range;
}
@Override
public Double fitnessFunction(List<Integer> ls) {
// TODO Auto-generated method stub
Double goal = (double) ls.stream().filter(n -> n > 0).count();
Double error = 0.;
Map<Huerto, List<Verdura>> huertoVerduras = new HashMap<>();
for(int i = 0; i < size(); i++) {
if(ls.get(i) > 0) {
Huerto huerto = DatosHuertos.getHuerto(ls.get(i) - 1);
if(huertoVerduras.containsKey(huerto)) {
Verdura verdura = DatosHuertos.getVerdura(i);
huertoVerduras.get(huerto).add(verdura);
} else {
Verdura verdura = DatosHuertos.getVerdura(i);
huertoVerduras.put(huerto, new ArrayList<>(List.of(verdura)));
}
}
}
error += penalizacionIncompatibilidad(huertoVerduras);
error += huertoVerduras.entrySet().stream()
.mapToInt(
e -> Math.abs(e.getKey().metrosDisponibles() -
e.getValue().stream()
.mapToInt(Verdura::metrosRequeridos)
.sum())
).sum();
return goal - 100000 * error;
}
private double penalizacionIncompatibilidad(Map<Huerto, List<Verdura>> huertoVerduras) {
double error = 0.;
for(Entry<Huerto, List<Verdura>> e: huertoVerduras.entrySet()) {
for(int i = 0; i < e.getValue().size() - 1; i++) {
List<Verdura> vs = e.getValue();
boolean b = vs.get(i).incompatibles().contains(vs.get(i+1).nombre());
error += b ? 1000 : 0;
}
}
return error;
}
@Override
public SolucionHuertos solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionHuertos.of_range(ls);
}
@Override
public Integer max(Integer i) {
// TODO Auto-generated method stub
return DatosHuertos.getM() + 1;
}
@Override
public Integer min(Integer i) {
// TODO Auto-generated method stub
return 0;
}
}

View File

@@ -0,0 +1,50 @@
package adda.ej1.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import adda.ej1.common.DatosHuertos.Huerto;
import adda.ej1.common.DatosHuertos.Verdura;
import us.lsi.common.Pair;
public class SolucionHuertos {
private static int index;
private static Integer distintas;
private static List<Pair<Verdura, Huerto>> solucion;
public static SolucionHuertos of_range(List<Integer> ls) {
return new SolucionHuertos(ls);
}
public SolucionHuertos() {
distintas = 0;
solucion = new ArrayList<>();
}
public SolucionHuertos(List<Integer> ls) {
index = 0;
solucion = new ArrayList<>();
ls.stream().forEach(hue -> {
if(hue > 0) {
Verdura v = DatosHuertos.getVerdura(index);
Huerto h = DatosHuertos.getHuerto(hue - 1);
solucion.add(Pair.of(v, h));
}
index++;
});
distintas = (int) solucion.stream()
.map(p -> p.first())
.distinct().count();
}
public String toString() {
String verduras = solucion.stream()
.map(p -> p.first().nombre() + ": Huerto " + p.second().nombre().replace("H", ""))
.collect(Collectors.joining("\n ", "Reparto de verduras y huerto en el que es plantada " +
"cada una de ellas (si procede):\n ", "\n"));
return String.format("%sVariedades cultivadas: %d", verduras, distintas);
}
}

View File

@@ -0,0 +1,40 @@
package adda.ej2;
import java.util.Locale;
import adda.ej2.common.BinaryCestaAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestCestaAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.10;
AlgoritmoAG.CROSSOVER_RATE = 0.9;
AlgoritmoAG.MUTATION_RATE = 0.75;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType = StoppingConditionFactory.StoppingConditionType.GenerationCount;
BinaryCestaAG p = new BinaryCestaAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej2/Ejercicio2DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej2/Ejercicio2DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej2/Ejercicio2DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,30 @@
package adda.ej2;
import java.io.IOException;
import java.util.Locale;
import adda.ej2.common.DatosCesta;
import adda.util.Titles;
import us.lsi.gurobi.GurobiLp;
import us.lsi.gurobi.GurobiSolution;
import us.lsi.solve.AuxGrammar;
public class TestCestaPLE {
public static void model(String fichero) throws IOException {
DatosCesta.iniDatos(fichero);
AuxGrammar.generate(DatosCesta.class, "modelos/ej2.lsi", "modelos/gurobi/ej2.lp");
Locale.setDefault(Locale.of("en", "US"));
GurobiSolution solution = GurobiLp.gurobi("modelos/gurobi/ej2.lp");
System.out.println(solution.toString());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.of("en", "US"));
System.out.println(Titles.F1);
model("ficheros/ej2/Ejercicio2DatosEntrada1.txt");
System.out.println(Titles.F2);
model("ficheros/ej2/Ejercicio2DatosEntrada2.txt");
System.out.println(Titles.F3);
model("ficheros/ej2/Ejercicio2DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,85 @@
package adda.ej2.common;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import adda.ej2.common.DatosCesta.Producto;
import us.lsi.ag.BinaryData;
public class BinaryCestaAG implements BinaryData<SolucionCesta>{
public BinaryCestaAG(String fichero) {
DatosCesta.iniDatos(fichero);
}
@Override
public Integer size() {
// TODO Auto-generated method stub
return DatosCesta.getN();
}
@Override
public Double fitnessFunction(List<Integer> ls) {
double goal = 0., error = 0.;
List<Producto> productos = new ArrayList<>();
if(ls.stream().filter(p -> p == 1).count() < DatosCesta.getM()) {
error += 1000000000;
} else {
// goal de precio
goal += getGoal(ls, productos);
// no cubrir todas las categorias
error += cumpleOrErrorSquared(productos.stream()
.map(Producto::categoria).distinct().count(),
p -> p.equals((long) DatosCesta.getM()));
// no cumplir media > 3
error += cumpleOrErrorSquared(productos.stream()
.mapToDouble(Producto::valoracion).sum()
- 3 * ls.stream().filter(p -> p > 0).count(), p -> p > 0);
// superar limite de presupuesto por categoria
error += cumpleOrError(
productos.stream().collect(
Collectors.groupingBy(Producto::categoria, Collectors.summingInt(Producto::precio))),
p -> p <= DatosCesta.getPresupuesto());
}
return -goal - 1000000000 * error;
}
private double getGoal(List<Integer> ls, List<Producto> productos) {
double res = 0.;
for(int i = 0; i < ls.size(); i++) {
if(ls.get(i) > 0) {
Producto p = DatosCesta.getProducto(i);
productos.add(p);
res += p.precio();
}
}
return res;
}
private <T extends Number> double cumpleOrErrorSquared(T res, Predicate<T> p) {
return p.test(res) ? 0. : Math.pow(res.doubleValue() * 10, 2);
}
private double cumpleOrError(Map<Integer, Integer> res, Predicate<Double> p) {
double ac = 0.;
for(Entry<Integer, Integer> e : res.entrySet()) {
double sum = e.getValue();
ac += p.test(sum) ? 0 : sum;
}
return Math.pow(ac, 2);
}
@Override
public SolucionCesta solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionCesta.of_list(ls);
}
}

View File

@@ -0,0 +1,85 @@
package adda.ej2.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosCesta {
public static int N; // productos
public static int M; // categorias
public static int PRES;
private static List<Producto> productos;
private static List<Integer> categorias;
public static record Producto(Integer id, Integer precio, Integer categoria, Integer valoracion) {
public static Producto of(String s) {
List<Integer> datos = Stream.of(s.split(":"))
.map(Integer::valueOf).toList();
return new Producto(datos.get(0), datos.get(1), datos.get(2), datos.get(3));
}
}
public static void toConsole() {
String2.toConsole("Presupuesto: %d", PRES);
String2.toConsole(productos, "Cesta de productos:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
List<String> productosStrings = lineas.subList(2, lineas.size());
PRES = Integer.valueOf(lineas.get(0).replace("Presupuesto = ", ""));
productos = new ArrayList<>();
for(String producto : productosStrings) {
productos.add(Producto.of(producto));
}
categorias = productos.stream().map(Producto::categoria).distinct().toList();
N = productos.size();
M = (int) productos.stream()
.map(Producto::categoria)
.distinct().count();
}
public static Integer getN() {
return N;
}
public static Integer getM() {
return M;
}
public static Integer getPrecio(Integer i) {
return productos.get(i).precio();
}
public static Integer getValoracion(Integer i) {
return productos.get(i).valoracion();
}
public static Integer getCategoria(Integer i) {
return productos.get(i).categoria();
}
public static Integer tieneCategoria(Integer i, Integer j) {
return productos.get(i).categoria.equals(categorias.get(j)) ? 1 : 0;
}
public static Integer getPresupuesto() {
return PRES;
}
public static Producto getProducto(int i) {
return productos.get(i);
}
public static void main(String[] args) {
iniDatos("ficheros/ej2/Ejercicio2DatosEntrada1.txt");
}
}

View File

@@ -0,0 +1,37 @@
package adda.ej2.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SolucionCesta {
private static Integer precioTotal;
private static List<Integer> solucion;
public static SolucionCesta of_list(List<Integer> ls) {
return new SolucionCesta(ls);
}
public SolucionCesta() {
precioTotal = 0;
solucion = new ArrayList<>();
}
public SolucionCesta(List<Integer> ls) {
solucion = new ArrayList<>();
precioTotal = 0;
for(int i = 0; i < ls.size(); i++) {
if(ls.get(i) > 0) {
precioTotal += DatosCesta.getProducto(i).precio();
solucion.add(DatosCesta.getProducto(i).id());
}
}
}
public String toString() {
String productos = solucion.stream()
.map(x -> "Producto " + x)
.collect(Collectors.joining(", ", "Productos elegidos: {", "}\n"));
return String.format("%sPrecio total de la cesta: %d", productos, precioTotal);
}
}

View File

@@ -0,0 +1,40 @@
package adda.ej3;
import java.util.Locale;
import adda.ej3.common.InRangeProductosTransportesAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestProductosTransportesAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.20;
AlgoritmoAG.CROSSOVER_RATE = 0.95;
AlgoritmoAG.MUTATION_RATE = 0.8;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType = StoppingConditionFactory.StoppingConditionType.GenerationCount;
InRangeProductosTransportesAG p = new InRangeProductosTransportesAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej3/Ejercicio3DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej3/Ejercicio3DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej3/Ejercicio3DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,30 @@
package adda.ej3;
import java.io.IOException;
import java.util.Locale;
import adda.ej3.common.DatosProductosTransportes;
import adda.util.Titles;
import us.lsi.gurobi.GurobiLp;
import us.lsi.gurobi.GurobiSolution;
import us.lsi.solve.AuxGrammar;
public class TestProductosTransportesPLE {
public static void model(String fichero) throws IOException {
DatosProductosTransportes.iniDatos(fichero);
AuxGrammar.generate(DatosProductosTransportes.class, "modelos/ej3.lsi", "modelos/gurobi/ej3.lp");
Locale.setDefault(Locale.of("en", "US"));
GurobiSolution solution = GurobiLp.gurobi("modelos/gurobi/ej3.lp");
System.out.println(solution.toString());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.of("en", "US"));
System.out.println(Titles.F1);
model("ficheros/ej3/Ejercicio3DatosEntrada1.txt");
System.out.println(Titles.F2);
model("ficheros/ej3/Ejercicio3DatosEntrada2.txt");
System.out.println(Titles.F3);
model("ficheros/ej3/Ejercicio3DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,90 @@
package adda.ej3.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosProductosTransportes {
public static int N; // productos
public static int M; // destinos
public static List<Destino> destinos;
public static List<Producto> productos;
public static record Destino(Integer id, Integer demanda) {
public static Destino of(String s) {
String[] partes = s.replaceAll("D(\\d+): demandaminima=(\\d+);", "$1,$2").split(",");
return new Destino(Integer.valueOf(partes[0]), Integer.valueOf(partes[1]));
}
}
public static record Producto(Integer id, Integer cantidad, List<Integer> coste) {
public static Producto of(String s) {
String[] partes = s.replace(" -> uds=", ";").replace(" coste_almacenamiento=", "").split(";");
String[] costes = partes[2].replaceAll("\\([0-9]+:", "").replace(")", "").split(",");
return new Producto(Integer.valueOf(partes[0].substring(1)), Integer.valueOf(partes[1]),
Stream.of(costes).map(Integer::valueOf).collect(Collectors.toList()));
}
}
public static void toConsole() {
String2.toConsole(destinos, "Destinos posibles:");
String2.toConsole(productos, "Productos del distribuidor:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
Integer aux = lineas.indexOf("// PRODUCTOS Id_producto -> unidades=integer;coste_almacenamiento=(destino:coste)");
List<String> d = lineas.subList(1, aux);
List<String> p = lineas.subList(aux + 1, lineas.size());
destinos = new ArrayList<>();
for(String destino : d) {
destinos.add(Destino.of(destino));
}
productos = new ArrayList<>();
for(String producto : p) {
productos.add(Producto.of(producto));
}
N = productos.size();
M = destinos.size();
}
public static Integer getN() {
return N;
}
public static Integer getM() {
return M;
}
public static Integer getCantidad(Integer i) {
return productos.get(i).cantidad();
}
public static Integer getDemanda(Integer j) {
return destinos.get(j).demanda();
}
public static Integer getCoste(Integer i, Integer j) {
return productos.get(i).coste().get(j);
}
public static Producto getProducto(int i) {
return productos.get(i);
}
public static List<Destino> getDestinos() {
return destinos;
}
public static void main(String[] args) {
iniDatos("ficheros/ej3/Ejercicio3DatosEntrada1.txt");
}
}

View File

@@ -0,0 +1,100 @@
package adda.ej3.common;
import java.util.List;
import us.lsi.ag.AuxiliaryAg;
import us.lsi.ag.ValuesInRangeData;
import us.lsi.ag.agchromosomes.ChromosomeFactory.ChromosomeType;
public class InRangeProductosTransportesAG implements ValuesInRangeData<Integer, SolucionProductosTransportes> {
private static Integer prods;
private static Integer dests;
public InRangeProductosTransportesAG(String fichero) {
DatosProductosTransportes.iniDatos(fichero);
prods = DatosProductosTransportes.getN();
dests = DatosProductosTransportes.getM();
}
@Override
public Integer size() {
// TODO Auto-generated method stub
return prods * dests;
}
@Override
public ChromosomeType type() {
// TODO Auto-generated method stub
return ChromosomeType.Range;
}
@Override
public Double fitnessFunction(List<Integer> ls) {
double goal = getCoste(ls);
double errorDem = penalizaDemanda(ls);
double errorProd = penalizaProductos(ls);
double error = errorDem + errorProd;
return -goal - 100000000 * error;
}
private double getCoste(List<Integer> ls) {
double res = 0.;
for(int i = 0; i < prods; i++) {
for(int j = 0; j < dests; j++) {
int pos = i * dests + j;
res += ls.get(pos) * DatosProductosTransportes.getCoste(i, j);
}
}
return res;
}
private double penalizaDemanda(List<Integer> ls) {
double res = 0.;
for(int j = 0; j < dests; j++) {
double dem = 0.;
for(int i = 0; i < prods; i++) {
int pos = i * dests + j;
dem += ls.get(pos);
}
res += AuxiliaryAg.distanceToEqZero(dem -
DatosProductosTransportes.getDestinos().get(j).demanda());
res += 1000 * AuxiliaryAg.distanceToGeZero(dem -
DatosProductosTransportes.getDestinos().get(j).demanda());
}
return res;
}
private double penalizaProductos(List<Integer> ls) {
double res = 0.;
for(int i = 0; i < prods; i++) {
double cantDest = 0.;
for(int j = 0; j < dests; j++) {
int pos = i * dests + j;
cantDest += ls.get(pos);
}
res += AuxiliaryAg.distanceToLeZero(cantDest -
DatosProductosTransportes.getProducto(i).cantidad());
}
return res;
}
@Override
public SolucionProductosTransportes solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionProductosTransportes.of_range(ls);
}
@Override
public Integer max(Integer i) {
// TODO Auto-generated method stub
return DatosProductosTransportes.getProducto(i / DatosProductosTransportes.getM()).cantidad() + 1;
}
@Override
public Integer min(Integer i) {
// TODO Auto-generated method stub
return 0;
}
}

View File

@@ -0,0 +1,45 @@
package adda.ej3.common;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SolucionProductosTransportes {
private static Map<Integer, List<Integer>> solucion;
private static Integer costeTotal;
public static SolucionProductosTransportes of_range(List<Integer> ls) {
return new SolucionProductosTransportes(ls);
}
public SolucionProductosTransportes() {
solucion = new HashMap<>();
costeTotal = 0;
}
public SolucionProductosTransportes(List<Integer> ls) {
solucion = new HashMap<>();
costeTotal = 0;
for(int i = 0; i < DatosProductosTransportes.getN(); i++) {
solucion.put(i, new ArrayList<>());
for(int j = 0; j < DatosProductosTransportes.getM(); j++) {
solucion.get(i).add(ls.get(i * DatosProductosTransportes.getM() + j));
costeTotal += ls.get(i * DatosProductosTransportes.getM() + j) *
DatosProductosTransportes.getCoste(i, j);
}
}
}
public String toString() {
String productos = solucion.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n",
"Reparto obtenido (cantidad de producto repartido a cada destino):\n" +
"//Destino m:[cantidad de producto n, cantidad de producto n+1, ...]\n",
"\n"));
return String.format("%sCoste total de almacenamiento: %d", productos, costeTotal);
}
}

View File

@@ -0,0 +1,40 @@
package adda.ej4;
import java.util.Locale;
import adda.ej4.common.PermutationPersonasAG;
import adda.util.Titles;
import us.lsi.ag.agchromosomes.AlgoritmoAG;
import us.lsi.ag.agstopping.StoppingConditionFactory;
public class TestPersonasAG {
@SuppressWarnings({ "rawtypes" })
private static void test(String fichero) {
Locale.setDefault(Locale.of("en", "US"));
AlgoritmoAG.ELITISM_RATE = 0.20;
AlgoritmoAG.CROSSOVER_RATE = 0.95;
AlgoritmoAG.MUTATION_RATE = 0.8;
AlgoritmoAG.POPULATION_SIZE = 1000;
StoppingConditionFactory.NUM_GENERATIONS = 1000;
StoppingConditionFactory.stoppingConditionType = StoppingConditionFactory.StoppingConditionType.GenerationCount;
PermutationPersonasAG p = new PermutationPersonasAG(fichero);
AlgoritmoAG alg = AlgoritmoAG.of(p);
alg.ejecuta();
System.out.println("================================");
System.out.println(alg.bestSolution());
System.out.println("================================");
}
public static void main(String[] args) {
System.out.println(Titles.F1);
test("ficheros/ej4/Ejercicio4DatosEntrada1.txt");
System.out.println(Titles.F2);
test("ficheros/ej4/Ejercicio4DatosEntrada2.txt");
System.out.println(Titles.F3);
test("ficheros/ej4/Ejercicio4DatosEntrada3.txt");
}
}

View File

@@ -0,0 +1,83 @@
package adda.ej4.common;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import us.lsi.common.Files2;
import us.lsi.common.String2;
public class DatosPersonas {
private static int N;
private static List<Persona> personas;
public static record Persona(Integer id, Integer edad, Set<String> idiomas,
String nacionalidad, List<Integer> afinidades) {
public static Persona of(String s) {
String[] partes = s.replaceAll("P(\\d+) -> ", "$1; ")
.replaceAll("\\s\\w+=","").split(";");
return new Persona(
Integer.valueOf(partes[0]),
Integer.valueOf(partes[1]),
Set.of(partes[2].replaceAll("[()\\s]","").split(",")),
partes[3],
List.of(partes[4].replaceAll("\\((\\d+):(\\d+)\\)", "$2").split(",")).stream()
.map(Integer::valueOf)
.toList()
);
}
}
public static void toConsole() {
String2.toConsole(personas, "Personas posibles:");
String2.toConsole(String2.linea());
}
public static void iniDatos(String fichero) {
List<String> lineas = Files2.linesFromFile(fichero);
List<String> personasStrings = lineas.subList(1, lineas.size());
personas = new ArrayList<>();
for(String persona : personasStrings) {
personas.add(Persona.of(persona));
}
N = personas.size();
}
public static Integer getN() {
return N;
}
public static Integer getAfinidad(Integer i, Integer j) {
j = i > j ? j : j - 1;
return personas.get(i).afinidades().get(j);
}
public static Integer getEdad(Integer i) {
return personas.get(i).edad();
}
public static Set<String> getIdiomas(Integer i) {
return personas.get(i).idiomas();
}
public static String getNacionalidad(Integer i) {
return personas.get(i).nacionalidad();
}
public static Boolean idiomaComun(Integer i, Integer j) {
Set<String> idiomas = new HashSet<>(personas.get(i).idiomas());
idiomas.retainAll(personas.get(j).idiomas());
return idiomas.size() >= 1;
}
public static Boolean mismaNacionalidad(Integer i, Integer j) {
return personas.get(i).nacionalidad().equals(personas.get(j).nacionalidad());
}
public static Boolean maximaDiferenciaEdad(Integer i, Integer j) {
return Math.abs(personas.get(i).edad() - personas.get(j).edad()) <= 5;
}
}

View File

@@ -0,0 +1,46 @@
package adda.ej4.common;
import java.util.List;
import us.lsi.ag.SeqNormalData;
import us.lsi.ag.agchromosomes.ChromosomeFactory.ChromosomeType;
public class PermutationPersonasAG implements SeqNormalData<SolucionPersonas> {
public PermutationPersonasAG(String fichero) {
DatosPersonas.iniDatos(fichero);
}
@Override
public ChromosomeType type() {
// TODO Auto-generated method stub
return ChromosomeType.Permutation;
}
@Override
public Double fitnessFunction(List<Integer> ls) {
double error = 0., goal = 0.;
for(int i = 0; i < ls.size() - 1; i+=2) {
goal += DatosPersonas.getAfinidad(ls.get(i), ls.get(i+1));
if(!DatosPersonas.idiomaComun(ls.get(i), ls.get(i+1))
|| DatosPersonas.mismaNacionalidad(ls.get(i), ls.get(i+1))
|| DatosPersonas.maximaDiferenciaEdad(ls.get(i), ls.get(i+1))) {
error += 10000;
}
}
return goal - 1000000 * error;
}
@Override
public SolucionPersonas solucion(List<Integer> ls) {
// TODO Auto-generated method stub
return SolucionPersonas.of_list(ls);
}
@Override
public Integer itemsNumber() {
// TODO Auto-generated method stub
return DatosPersonas.getN();
}
}

View File

@@ -0,0 +1,37 @@
package adda.ej4.common;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import us.lsi.common.Pair;
public class SolucionPersonas {
private static List<Pair<Integer,Integer>> solucion;
private static Integer sumaAf;
public static SolucionPersonas of_list(List<Integer> ls) {
return new SolucionPersonas(ls);
}
public SolucionPersonas() {
sumaAf = 0;
solucion = new ArrayList<>();
}
public SolucionPersonas(List<Integer> ls) {
sumaAf = 0;
solucion = new ArrayList<>();
for(int i = 0; i < ls.size() - 1; i+=2) {
solucion.add(Pair.of(ls.get(i), ls.get(i+1)));
sumaAf += DatosPersonas.getAfinidad(ls.get(i), ls.get(i+1));
}
}
public String toString() {
String personas = solucion.stream()
.map(p -> "(" + p.first() + ", " + p.second() + ")")
.collect(Collectors.joining(", ", "Relación de parejas:\n[", "]\n"));
return String.format("%sSuma de afinidades: %d", personas, sumaAf);
}
}

View File

@@ -0,0 +1,41 @@
package adda.util;
public class Titles {
public static String F1 =
"""
####### ### # ####### #
# # # # ##
# # # # # #
##### # # ##### #
# # # # #
# # # # #
# ### ####### ####### #####
""";
public static String F2 =
"""
\n\n\n
####### ### # ####### #####
# # # # # #
# # # # #
##### # # ##### #####
# # # # #
# # # # #
# ### ####### ####### #######
""";
public static String F3 =
"""
\n\n\n
####### ### # ####### #####
# # # # # #
# # # # #
##### # # ##### #####
# # # # #
# # # # # #
# ### ####### ####### #####
""";
}

10
PI4/src/module-info.java Normal file
View File

@@ -0,0 +1,10 @@
module PI4 {
requires solve;
requires partecomun;
requires geneticos;
requires datos_compartidos;
exports adda.ej1;
exports adda.ej2;
exports adda.ej3;
exports adda.ej4;
}