【问题标题】:How to convert a matrix consisting entirely of 1's?如何转换完全由 1 组成的矩阵?
【发布时间】:2015-10-30 07:49:17
【问题描述】:

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

规则:矩阵周围有按钮。每次按下按钮时,相关的行/列/对角线都会从 0 切换到 1(反之亦然)。假设只给出了可解矩阵。例如(灰色为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

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

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

【问题讨论】:

  • 我猜你之前也发过类似的问题。
  • 我放弃了解决4X3矩阵的情况,如果我连这个特殊情况都解决不了,我就放弃了。
  • 只是想知道为什么您需要在按钮 6 上单击两次。
  • 这个例子不是最优解,所以任何可能的路径都足够了。
  • 有 1024 种可能的开关组合。您可以全部尝试。

标签: r algorithm matrix


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2019-12-12
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多