2016-08-02 25 views
3

对于自分配的项目全部九位数字矩阵,我决定尝试和创建井字棋的每一个可能的游戏。为了存储和表示这些游戏,我决定使用9列362880行的矩阵。每行是一个游戏,其中奇数列是“X”的移动,偶数列是“O”的移动。创建一个不包含重复整数

(1,2,3,4,5,6,7,NULL,NULL)表示游戏,其中X获胜。

enter image description here

这就是为什么我要生成一个不包含重复的整数,作为重复整数意味着玩家试图以纪念一个已经占用的位置逢九个位数。

下面是一个可能的方法的开端

#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) 
} 

输出:

enter image description here

现在很明显的问题是,每行都是相同的,而我希望他们每一个都可以独特。而我不能为我的生命弄清楚是如何重新排列

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

每隔数到每一个可能的组合。

+4

要生成所有排列。这[SO接听](http://stackoverflow.com/questions/11095992/generating-all-distinct-permutations-of-a-list-in-r)就行了。 – aichao

+1

考虑到游戏可以在最后一步之前结束,一棵树看起来更自然。此外,你还不如折叠所有旋转和翻转对称:让第一招是“角”,“侧面”或“中等”和其他定义相对于该移动。 – Frank

+1

一个很好的数据结构将是有一些孩子和值(矩阵你的情况)递归树。分支将是允许从该位置移动,或者只是所有可能的移动,然后清理。 – FisherDisinformation

回答

1

如果你愿意用另一个包,您可以通过直接做到这一点:

library(combinat) 

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

因为有9个单元,所以他们不需要0。 – Frank

+1

是的,它应该是'permn(seq_len(9))'。因为它为'10'元素生成所有排列,因此你有'10!'行而不是所请求的'9!'行。我知道OP已经接受你的答案,但请修复。 – aichao

+1

这工作,但我最终删除了“0”。我试图从你自己的答案中删除它,但编辑太小,我无法制作。 – user2533660

1

如果你只是在寻找下表:

library(permute) 
all_games <- allPerms(1:9, how(maxperm=1e10))