Here is the data I'm working with:
structure(list(Name = c("Jokic", "Butler", "Murray", "Adebayo",
"Porter", "Gordon", "Martin", "Pope", "Vincent", "Lowry", "Brown",
"Strus", "Robinson", "Green", "Highsmith"), Points = c(62.8,
48.8, 45.8, 41.8, 35.3, 30.3, 29.3, 23.8, 23.3, 22.3, 21.8, 19,
16.3, 8.5, 6.8), Cost = c(14000, 13400, 10800, 9200, 7600, 6600,
7400, 5600, 5800, 5200, 6200, 4800, 4200, 2200, 1400)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -15L))
Here's my current code:
library(readxl)
library(tidyverse)
library(lpSolveAPI)
# Read the data from Excel
data <- read_excel("C:/Users/M0185JN/Downloads/NBA_1.xlsx")
data$cpt_points <- 1.5*data$Points
data$cpt_cost <- 1.5*data$Cost
#Players
num_players <- rep(1,nrow(data))
num_captain <- rep(1,nrow(data))
# Define the objective function coefficients
obj <- data$Points*num_players + data$cpt_points*num_captain
# Create a new LP model
lprec <- make.lp(nrow(data), nrow(data))
# Set the optimization direction to maximize
lp.control(lprec, sense = "maximize")
# Set the objective function coefficients
set.objfn(lprec, obj)
# Set type of decision variables
set.type(lprec, 1:nrow(data), type = "binary")
# Constraint: Pick exactly 5 players
add.constraint(lprec, num_players, "=", 5)
add.constraint(lprec, num_captain, "=", 1)
# Constraint: Total cost must be less than or equal to 50,000
add.constraint(lprec, data$Cost*num_players + data$cpt_cost*num_captain, "<=", 50000)
# Constraint: No Duplicate Players
add.constraint(lprec, num_players + num_captain, "<=", 1)
# Solve the linear programming problem
solve(lprec)
# Get the solution status
status <- get.solutioncount(lprec)
# Check if a solution was found
if (status > 0) {
# Retrieve the values of the decision variables
player_picked <- get.variables(lprec)
# Create a data frame with the players and their corresponding picked status
result <- data.frame(Name = data$Name, Picked = player_picked)
# Filter the data frame to show only the players that were picked (Picked = 1)
picked_players <- result[result$Picked == 1, ]
# Print the picked players
print(picked_players)
} else {
print("No feasible solution found.")
}
The code is continuing to give me a "No Feasible Solution Found." when I know for a fact there is. Here are the constraints better explained:
- I have to pick 6 players
- 1 is going to get cpt_points and cpt_cost while the others are getting Points and Cost.
- You can also not pick the same player to get both.
- Total cost cannot exceed 50000.
Some suspicious stuff, like the "number-of" variables which should probably instead be assignment vectors where the captain is not considered a player. The following succeeds but I have not translated it back to R.
If it turns out that you really do want six players, then change the
4to5and this produces