user2533660 - 7 months ago 51

R Question

For a self-assigned project, I decided to try and create every possible game of tic-tac-toe. To store and represent each of these games, I decided to use a matrix with 9 columns and 362880 rows. Each row is one game, where the odd columns are "X's" moves and the even columns are "O's" moves.

(1,2,3,4,5,6,7,NULL,NULL) represents a game where X wins.

This is why I want to generate every nine digit number that does not contain duplicate integers, as a duplicate integer would mean that a player tried to mark a position that is already occupied.

Below is the beginnings of one possible method

`#create matrix that can contain all possible arrangements of moves on a tic-tac-toe board`

tictactoematrix <- matrix(ncol = 9, nrow = 362880)

j = 1

k = 1

#create list of possible moves

move <- list(1,2,3,4,5,6,7,8,9)

#populate every row with numbers 1-9

for(i in 1:362880){

tictactoematrix[i,1] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,2] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,3] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,4] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,5] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,6] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,7] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,8] <- move[[1]]

move[1] <- NULL

tictactoematrix[i,9] <- move[[1]]

move[1] <- NULL

move <- list(1,2,3,4,5,6,7,8,9)

}

The output:

Now obviously the problem with is that every row is identical, while I want them to each be unique. And what I can't for the life of me figure out is how to rearrange every number in the

`move <- list(1,2,3,4,5,6,7,8,9)`

into every possible combination.

Answer

If you're willing to use another package, you can do this directly via:

```
library(combinat)
temp <- permn(c(1,2,3,4,5,6,7,8,9))
fullTable <- do.call("rbind", temp)
```