如何在R中将Pin Pad创建为矩阵?

时间:2019-06-21 17:43:24

标签: r

我正在处理一些机器人问题,我想以矩阵形式创建ATM密码键盘

到目前为止,我能想到的是

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,依此类推,直到该行已满为止,因为它们将不会在图形中形成

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

 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中实现这一目标?

1 个答案:

答案 0 :(得分:3)

简单/小助手功能:

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