Home > Net >  R lpSolve setting constraints (fantasy football related)
R lpSolve setting constraints (fantasy football related)

Time:05-09

I am trying to solve linear optimization problem. I have 100 players with score and price for each player. My goal is to select 11 players and to maximize possible score while staying within budget (83 in this example). Code below solve this task.

library(data.table)
library(lpSolve)
set.seed(1)
# simulating data
data <- data.table(id = 1:100,
                   price = round(rnorm(100, 9, 2), 1),
                   score = round(rnorm(100, 150, 25)))
# objective which should be maximized
obj <- data$score

constraints <- matrix(
  c(data$price, 
    rep(1, 100)),
  byrow = TRUE, nrow = 2
)

constr_dir <- c("<=", "==")

rhs <- c(83, 11)

result <- lp("max", obj, constraints, constr_dir, rhs, all.bin = TRUE)

# joining result for easier observing
data$result <- result$solution
data[result != 0,]

Here is the question. In my team should be a captain whose score will count twice. How do I modify my code to add this condition? (please pay attention to all.bin argument in lp function, maybe this should be changed in final solution). So here is current result:

    id price score coeff
 1:  6   7.4   194     1
 2: 10   8.4   192     1
 3: 13   7.8   186     1
 4: 14   4.6   134     1
 5: 24   5.0   146     1
 6: 35   6.2   158     1
 7: 60   8.7   197     1
 8: 66   9.4   205     1
 9: 71  10.0   208     1
10: 78   9.0   202     1
11: 97   6.4   186     1

What I want to achieve is 10 coefficients should be equal to 1 and one equal to 2(result may differ from one below, this is an example):

    id price score coeff
 1:  6   7.4   194     1
 2: 10   8.4   192     1
 3: 13   7.8   186     1
 4: 14   4.6   134     1
 5: 24   5.0   146     1
 6: 35   6.2   158     1
 7: 60   8.7   197     1
 8: 66   9.4   205     1
 9: 71  10.0   208     2
10: 78   9.0   202     1
11: 97   6.4   186     1

CodePudding user response:

You can run 100 augmented linear problems. In ith problem you multiple score of ith player by 2. At then end you pick solution with highest score:

constraints <- matrix(c(data$price, rep(1, 100)), byrow = TRUE, nrow = 2)
constr_dir <- c("<=", "==")
rhs <- c(83, 11)

res <- vector("list", nrow(data))
for(i in seq_len(nrow(data))){
  
  cat("iter:", i, "\n")

  obj <- data$score
  obj[[i]] <- obj[[i]] * 2
  
  res[[i]] <- lp("max", obj, constraints, constr_dir, rhs, all.bin = TRUE)
}

captain_index <- which.max(unlist(lapply(res, function(x) x$objval)))
data[res[[captain_index]]$solution == 1,]

chosen captain has index captian_index

  • Related