首页 > 解决方案 > 如何在 R 中将 Pin Pad 创建为矩阵?

问题描述

我正在研究一些机器人问题,我想以矩阵的形式创建一个 ATM Pin Pad

到目前为止我能想到的是

items = 10;
width = 3;

x <- 1:9
length(x) <- prod(dim(matrix(x, ncol = width)))
## you will get a warning here unless suppressWarnings() is used except for width = 3
Pad = matrix(x, ncol = width, byrow = TRUE)

if(width == 1)
  Pad = rbind(Pad, c(0))

if(width == 9)
  Pad = cbind(Pad, c(0))`

我面临的问题是宽度可以是可变数量,因此在末尾(9 之后)放置零会产生问题。此外,如果我以某种方式将始终放在最后一行的零,则 0 之后的任何内容都应该是 -1、-2 等等,直到行满,因为它们不会被考虑在图表中形成

示例:如果宽度为 3,我现在已经明确处理宽度 1 和 9 的情况,我需要类似的东西

 1 2 3
 4 5 6
 7 8 9
 0 -1 -2

如果宽度为 4

 1 2 3 4
 5 6 7 8
 9 0 -1 -2

如果宽度为 5

 1 2 3 4 5
 6 7 8 9 0

我怎样才能在 R 中实现这一点?

标签: r

解决方案


简单/小型辅助功能:

mypad <- function(nrow, ncol) {
  if (missing(nrow)) nrow <- ceiling(10L / ncol)
  if (missing(ncol)) ncol <- ceiling(10L / nrow)
  x <- c(1:9, 0L)
  length(x) <- prod(nrow, ncol)
  x[ is.na(x) ] <- -seq_len(sum(is.na(x)))
  matrix(x, nrow = nrow, ncol = ncol, byrow = TRUE)
}

采用:

mypad(ncol=3)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6
# [3,]    7    8    9
# [4,]    0   -1   -2
mypad(ncol=4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]    5    6    7    8
# [3,]    9    0   -1   -2
mypad(ncol = 3)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6
# [3,]    7    8    9
# [4,]    0   -1   -2
mypad(ncol = 4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    2    3    4
# [2,]    5    6    7    8
# [3,]    9    0   -1   -2
mypad(ncol = 5)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    6    7    8    9    0
mypad(ncol = 6)
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    2    3    4    5    6
# [2,]    7    8    9    0   -1   -2

推荐阅读