This transportation problem is solved using the ‘lpsolve’ package in R. There is no transparency about which method is used. It gives the right answer in terms of allocations and the optimal cost. Explanability of the model could be an issue. I wanted to put this disclaimer upfront.
# Load lpSolve
library(lpSolve)
# Define the cost matrix
costs <- c(19, 30, 50, 10,
70, 30, 40, 60,
40, 8, 70, 20)
# Supply and Demand
supply <- c(7, 9, 18)
demand <- c(5, 8, 7, 14)
# The number of suppliers and demand points
n_supply <- length(supply)
n_demand <- length(demand)
# Create the constraint matrix
constraint_matrix <- matrix(0, nrow = n_supply + n_demand, ncol = n_supply * n_demand)
# Supply constraints
for (i in 1:n_supply) {
constraint_matrix[i, ((i - 1) * n_demand + 1):(i * n_demand)] <- 1
}
# Demand constraints
for (j in 1:n_demand) {
indices <- seq(from = j, to = n_supply * n_demand, by = n_demand)
constraint_matrix[n_supply + j, indices] <- 1
}
# Combine supply and demand into a single vector
rhs <- c(supply, demand)
# Constraint types: all constraints are equality
constraint_types <- rep("=", n_supply + n_demand)
# Solve the linear program
lp_solution <- lp("min", costs, constraint_matrix, constraint_types, rhs, all.int = TRUE)
# Check the solution status
if (lp_solution$status == 0) {
optimal_values <- matrix(lp_solution$solution, nrow = n_supply, byrow = TRUE)
print("Optimal transportation quantities:")
print(optimal_values)
# Calculate the optimal cost
optimal_cost <- sum(optimal_values * matrix(costs, nrow = n_supply, byrow = TRUE))
cat("Optimal cost:", optimal_cost, "\n")
} else {
print("No optimal solution found")
}
## [1] "Optimal transportation quantities:"
## [,1] [,2] [,3] [,4]
## [1,] 5 0 0 2
## [2,] 0 2 7 0
## [3,] 0 6 0 12
## Optimal cost: 743