I am trying to program tic-tac-toe in R - here are my two functions for making a move and evaluating all valid moves (the ones are X's, zeros are O's and NA is not taken yet):
move <- function(board,square,mark) { if (square < 1 || square > 9 || !is.na(board[square])) { return(NA) } else board[square] <- mark return(board) } valid.moves <- function(board) { return(which(is.na(board))) } Now setting up a test position, evaluating all valid moves and then make those moves...
test.last <- matrix(c(1,1,NA,0,NA,0,NA,0,1),nrow=3) moves <- valid.moves(test.last) move(test.last,moves,1) ...gives a result which I didn't intend:
[,1] [,2] [,3] [1,] 1 0 1 [2,] 1 1 0 [3,] 1 0 1 I wanted to have three different boards with the respective valid moves (which will then be evaluated with another function whether it is a winning position) and not one board with all valid moves made at once.
I don't want to do this with a loop but the vectorization should not take place all at once 'inside' the move function but 'outside' of it - so basically I want to do the following without a loop (the eval.pos function to evaluate the position is of the form eval.pos <- function(board){}):
for (i in 1:length(moves)) { after.moves <- move(test.last,moves[i],1) print(after.moves) print(eval.pos(after.moves)) } How can I accomplish this without a loop?
mapply, see -perhaps- something likeVectorize(move, "square", SIMPLIFY = F)(test.last, moves, 1)whichreturns a length-3 vector in this case. You might have had better luck using the arr.ind=TRUE option so you could identify the matrix indices.