如何转换完全由1组成的矩阵?

时间:2015-10-30 07:49:17

标签: r algorithm matrix

我想在游戏中完成一般化路线(https://www.youtube.com/watch?v=3ie4Z2odRjU)。目标是获得一个可能的(不一定是最优的)序列,使得给定的4x3矩阵完全由1组成。

规则:矩阵周围有按钮。每按一次按钮,相对行/列/对角线将0s切换为1s(反之亦然)。假设只给出可解矩阵。例如(灰色为0):

m=matrix(c(1,0,1,1,0,1,1,1,0,0,0,1), nr=4)
1 0 0
0 1 0
1 1 0
1 1 1

enter image description here enter image description here

通过按下按钮8,9,7,6,6,5,4,1将矩阵转换为仅由1组成的矩阵。所以期望的结果是c(8,9,7,6,6, 5,4,1)

我猜两个核心是表示算法相互转换0和1(可能与递归一起?我不知道。),并表达操作(在这种情况下,因为输入有10个操作无论如何,矩阵是4乘3),这似乎超出了我的能力。

1 个答案:

答案 0 :(得分:0)

f <- list(`1` = function(x) {diag(x) <- !diag(x); x},
          `2` = function(x) {x[1,] <- !x[1,]; x},
          `3` = function(x) {x[2,] <- !x[2,]; x},
          `4` = function(x) {x[3,] <- !x[3,]; x},
          `5` = function(x) {x[4,] <- !x[4,]; x},
          `6` = function(x) {x[4,1] <- !x[4,1]; x[3,2] <- !x[3,2]; x[2,3] <- !x[2,3]; x},
          `7` = function(x) {x[,1] <- !x[,1]; x},
          `8` = function(x) {x[,2] <- !x[,2]; x},
          `9` = function(x) {x[,3] <- !x[,3]; x},
          `10` = function(x) {diag(x[-1,]) <- !diag(x[-1,]); x})

exef <- function(mat, action_vector) {
  require("magrittr")
  paste0("mat %>% f$`", paste(action_vector, collapse = "`(.) %>% f$`"), "`(.)") %>%
    parse(text = .) %>% eval
}

all_possible_actions_list <- lapply(1:10, function(i) {
  actions <- combn(1:10, i)
  unname( split(t(actions), 1:ncol(actions)) )
  }) %>% unlist(recursive = F)

msolution <- function(m) {
  for (k in 1:length(all_possible_actions_list)) {
    if (sum(exef(m, all_possible_actions_list[[k]])) == 12) break
  }
  all_possible_actions_list[[k]]
}

msolution(m)
# 1 2 3