my solution, I chose to parallelise using furrr as I got impatient for the result
library(tidyverse)
library(furrr)
library(progressr)
df <- tibble::tribble(
~players, ~score, ~index, ~role,
"player 1", 7.6522345055826, 7.89539316063747, "C",
"player 2", 14.0114752201363, 5.928034061566, "F",
"player 3", 9.19400690700859, 5.40506813768297, "F",
"player 4", 15.2143210308626, 8.94269776623696, "G",
"player 5", 15.9439345105318, 5.55705799115822, "G",
"player 6", 4.57856754225213, 6.08530468167737, "C",
"player 7", 10.7069396981969, 4.44066024711356, "F",
"player 8", 15.3337218638044, 4.9414202044718, "F",
"player 9", 11.003224683716, 1.8915973729454, "G",
"player 10", 9.79900713835377, 0.471136473119259, "G",
"player 11", 16.1517834859435, 8.63024232536554, "C",
"player 12", 9.7573437836254, 8.02299045119435, "F",
"player 13", 12.6051470702514, 5.90705278422683, "F",
"player 14", 11.2724442048464, 6.95467417687178, "G",
"player 15", 5.30714346985333, -0.753863154910505, "G",
"player 16", 15.4277771241032, 3.77795971091837, "C",
"player 17", 7.12531422630418, 6.58459537522867, "F",
"player 18", 4.53415607584175, 1.16407935833558, "F",
"player 19", 8.16459313489031, 2.18181007634848, "G",
"player 20", 16.1221963441698, 1.31625785352662, "G"
)
best_x <- function(x,n){
candidates_df <- filter(df,
role==x)
combs_1 <- combn(candidates_df$players,n,simplify = FALSE)
imap_dfr(combs_1,~{
filter(candidates_df,players %in% .x) %>% mutate(combination=.y) %>%
rename_at(.vars = "combination",~paste0(x,"_comb"))
})
}
c_set <- best_x("C",2)
f_set <- best_x("F",4)
g_set <- best_x("G",4)
all_combinations <- expand_grid(C_comb=unique(pull(c_set,C_comb)),
F_comb=unique(pull(f_set,F_comb)),
G_comb=unique(pull(g_set,G_comb)))%>%
mutate(comb_id=row_number()) %>% relocate(comb_id)
(todo <- nrow(all_combinations))
plan(multisession, workers = 6)
with_progress({
p <- progressor(steps = todo)
all_comb_detail <- future_pmap_dfr(.l = all_combinations,
.f = ~{
p(..1)
res <- bind_rows(filter(c_set,C_comb==..2),
filter(f_set,F_comb==..3),
filter(g_set,G_comb==..4)
) %>% mutate(comb_id=..1)
res
})
},interval = 1L)
(valid_score_sums <- group_by(all_comb_detail,
comb_id) %>% summarise(ss=sum(score),
valid_score_range=between(ss,95.5,100.4),
sum_index = sum(index)))
top_10_teams <- filter(valid_score_sums,valid_score_range) %>% slice_max(order_by=sum_index,n=10)
(top_10_teams_detials <- top_10_teams %>% left_join(all_comb_detail))