In [1]:
using GLPKMathProgInterface # Loading the GLPK module for using its solver
using JuMP
In [2]:
# Define Data
Water = [0 0 0 1 0 0 0 0 ;
0 0 0 0 0 0 0 0 ;
0 0 0 0 0 0 0 0 ;
0 1 1 0 0 0 1 0 ;
0 0 0 1 0 0 0 0 ;
1 0 0 0 1 0 1 0 ;
0 0 0 1 1 1 0 0 ;
0 0 0 0 0 0 0 0 ]
Wood= [0 0 0 0 0 0 0 1 ;
1 0 0 0 0 0 0 0 ;
0 0 0 0 0 0 0 0 ;
0 0 0 0 1 0 0 0 ;
0 0 1 0 0 0 0 1 ;
0 0 0 0 0 0 1 1 ;
0 0 0 0 0 0 0 0 ;
0 0 0 0 0 0 0 0 ]
Swamp = [0 0 0 0 0 0 1 0 ;
0 0 0 1 0 0 0 0 ;
1 0 0 0 0 0 0 0 ;
1 0 1 0 0 0 0 0 ;
0 0 0 0 0 0 1 0 ;
0 0 0 0 0 0 0 1 ;
0 0 0 1 0 1 0 0 ;
0 1 0 0 0 0 0 0 ]
Mosquitos = [0 0 1 0 0 0 0 0;
0 0 0 0 0 0 0 0;
1 0 0 0 0 0 0 1;
0 0 1 0 0 0 0 0;
0 0 0 0 0 0 0 0;
1 0 0 0 0 0 1 0;
0 1 0 0 0 0 0 0;
0 0 0 0 0 0 1 0]
Out[2]:
In [3]:
elements = ["Water","Wood","Swamp", "Mosquitos"]
Out[3]:
In [4]:
CostAt = ["Water"=> 3, "Wood"=> 2, "Swamp" => -2 , "Mosquitos"=>-3]
Out[4]:
In [7]:
CostNear = ["Water"=> 1, "Wood"=> 1, "Swamp" => -1,"Mosquitos"=>-2, ]
Out[7]:
In [9]:
#MODEL CONSTRUCTION
#--------------------
m = Model(solver=GLPKSolverLP())
#define initial variables
@defVar(m, quality[elements,1:8,1:8] )
@defVar(m, score[1:8,1:8] )
Out[9]:
In [11]:
#define quality constraint
for i = 1:8
for j = 1:8
for ki in [0,1, -1]
for kj in [0,1,-1]
if i + ki >= 1 && i + ki <= 8 && j + kj >= 1 && j+kj <= 8
for e in elements
if kj == 0 && ki == 0
if e == "Water"
@addConstraint(m, quality[e,i,j] >= Water[i + ki, j + kj] * CostAt["Water"])
elseif e == "Wood"
@addConstraint(m, quality[e,i,j] >= Wood[i + ki, j + kj] * CostAt["Wood"])
elseif e == "Swamp"
@addConstraint(m, quality[e,i,j] <= Swamp[i + ki, j + kj] * CostAt["Swamp"])
elseif e == "Mosquitos"
@addConstraint(m, quality[e,i,j] <= Mosquitos[i + ki, j + kj] * CostAt["Mosquitos"])
end
else
if e == "Water"
@addConstraint(m, quality[e,i,j] >= Water[i + ki, j + kj] * CostNear["Water"])
elseif e == "Wood"
@addConstraint(m, quality[e,i,j] >= Wood[i + ki, j + kj] * CostNear["Wood"])
elseif e == "Swamp"
@addConstraint(m, quality[e,i,j] <= Swamp[i + ki, j + kj] * CostNear["Swamp"])
elseif e == "Mosquitos"
@addConstraint(m, quality[e,i,j] <= Mosquitos[i + ki, j + kj] * CostNear["Mosquitos"])
end
end
end
end
end
end
end
end
In [12]:
for i in 1:8
for j in 1:8
@addConstraint(m, score[i,j] == sum{quality[e,i,j] , e in ["Water","Wood"]}
-sum{quality[e,i,j] , e in ["Swamp","Mosquitos"]}
)
end
end
In [13]:
#define objective
@setObjective(m, Min, sum{score[i,j], i=1:8, j=1:8})
Out[13]:
In [14]:
#print(m)
In [15]:
#print(m)
status = solve(m)
Out[15]:
In [16]:
max_x = 1
max_y = 1
maxval = 0
sumquality = zeros(8,8)
for i in 1:8
for j in 1:8
for e in elements
sumquality[i,j] += getValue(quality[e,i,j])
end
print(sumquality[i,j])
print("\t")
if maxval <= sumquality[i,j]
max_x = i
max_y = j
maxval = sumquality[i,j]
end
end
println()
end
print("best campsite is at $(max_x), $(max_y)")
In [27]:
In [ ]: