C.J.P
C.J.P

Reputation: 11

For Loop in R for snake draft?

I am fairly new to R, and am trying to automate a snake draft in R with a for loop. Essentially, I want to take a vector that has 9 columns (for each of the 9 teams) and take the first available player in that column (all 9 teams have a varying order of the same 36 players; ranked how each team captain feels the player will perform) and put it in a blank matrix that will ultimately have all the teams finalized.

As I have stated, there are 9 teams each drafting 4 players. Because it is a snake draft the "picking order" runs like this:

all the way to

and this follows suit back to

Because there are 9 Team Captains and 36 players to chose from, each team ultimately has four players (non-repeating). I hope I have explained this well enough. I love this site, and appreciate your help!

Upvotes: 1

Views: 235

Answers (2)

alistaire
alistaire

Reputation: 43354

Here's a reasonably readable version:

set.seed(47)

players <- cbind(replicate(9, sample(1:36)), ID = 1:36)    # column 10 is ID column
pick <- matrix(NA, 4, 9)    # matrix to fill

for(round in 1:4){
    direction <- if(round %% 2 == 1) {1:9} else {9:1}
    for(team in direction){
        pick[round, team] <- players[which.min(players[, team]), 'ID']    # store pick
        players <- players[-which.min(players[, team]), , drop = FALSE]    # erase player's row
    }
}

pick    # rows are rounds, columns are teams, numbers are player IDs
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,]   18    5   20    6   27   36   24   34   26
# [2,]   19   28   32    1   23   33   30    2   17
# [3,]   21   15    8    9   13    7   35   31   14
# [4,]   16    3    4   22   10   11   29   25   12

Upvotes: 0

Adam Quek
Adam Quek

Reputation: 7163

Here's a propose solution. Not the most elegant looking but should work for your problem:

players <- paste0("player", 1:36)
picks<-sample(players, 36)
draft <- matrix(NA, ncol=9, nrow=4)
for(i in 1:4){
  if(i %in% c(1,3)) draft[i, 1:9] <- picks[(9*(i-1)+1):(9*(i-1)+ 9)]
  if(i %in% c(2,4)) draft[i, ] <- rev(picks[(9*(i-1)+1):(9*(i-1)+ 9)])
}


draft
     [,1]       [,2]       [,3]       [,4]       [,5]       [,6]       [,7]       [,8]       [,9]      
[1,] "player4"  "player12" "player29" "player10" "player19" "player26" "player3"  "player21" "player20"
[2,] "player17" "player7"  "player9"  "player5"  "player6"  "player23" "player15" "player35" "player13"
[3,] "player36" "player34" "player28" "player32" "player33" "player27" "player30" "player31" "player8" 
[4,] "player11" "player22" "player2"  "player18" "player24" "player25" "player16" "player1"  "player14"

Upvotes: 1

Related Questions