如何随机排列元素?

How do I randomly arrange elements?

我正在使用 R 控制台针对指定的网格维度(n_rown_col)创建记忆游戏。我想在运动场上随机排列卡片(玩家不可见)。每对相同的卡片应对应于符号 (pch) 和颜色 (col) 的唯一组合。我该怎么做?

这是我当前的代码:

memory <- function(n_row = 6, n_col = 6, pch = 1:13, col = 1:8, n_player = 2) {

 # Select starting player
 player <- sample(1:n_player, 1, replace = TRUE) 

 # Print starting message
 cat(paste0("Player", player, "starts!"))
 cat(paste0("In each move you have to choose two cards."))

 # Stop function if n is odd
 n <- n_row * n_col
 if(n %% 2 != 0) 
   stop("Error in memory(): n_row * n_col must be an even number.")

 # Otherwise arrange cards randomly

}

R 是一种统计编程语言,掷骰子和纸牌游戏是它的强项;-)。它们自然可以用向量和矩阵表示。假设每张卡都有一个整数代码,例如1到12,然后我们只需要混合它们然后re-format它作为矩阵:

## twelve pairs of cards
cards <- rep(1:12, each=2)

## mix the cards
mixed <- sample(cards)

## arrange it at a gameboard
gameboard <- matrix(mixed, nrow=4, ncol=6)

## show placement of cards as a matrix
gameboard

## a simple visualization
image(gameboard, col=rainbow(12))

要以图形方式在网格上排列符号或数字,可以直接使用矢量并使用 %%(取模)和 %/%(整数除法)来计算坐标:

## arrange symbols or numbers at a grid
plot(NULL, xlim=c(0, 6), ylim=c(0, 4), axes=FALSE, xlab="", ylab="")
text(0.5 + (1:24 %% 6), 0.5 + (0:23 %/% 6), mixed)
box()
abline(h=seq(-0, 4), lty="dashed")
abline(v=seq(-0, 6), lty="dashed")

只是回答如何标记符号的问题:

n_row = 6
n_col = 6
pch = 1:13
col = 1:8

x <- setNames(expand.grid(pch, col), c("pch", "col"))
x2 <- x[sample(seq_len(nrow(x)), n_row*n_col*.5), ]
x2 <- rbind(x2, x2)[sample(seq_len(n_row*n_col)), ]

# Plot
plot(NULL, xlim=c(0, n_col), ylim=c(0, n_row), axes=FALSE, xlab="", ylab="")
box(lwd = 2)
abline(h=seq(0, n_row), lty="dashed")
abline(v=seq(0, n_col), lty="dashed")
points(0.5 + (1:(n_row*n_col) %% n_col), 0.5 + (0:((n_row*n_col) -1) %/% n_col), 
    pch=x2$pch, col=x2$col, cex=3)

reprex package (v2.0.1)

创建于 2022-05-31