编程介的小学生 2019-12-06 22:44 采纳率: 0.4%
浏览 104

Fill the blanks 填空的问题

Problem Description
There is a matrix of 4*4, you should fill it with digits 0 – 9, and you should follow the rules in the following picture:

Input
No input.

Output
Print all the matrixs that fits the rules in the picture.
And there is a blank line between the every two matrixs.

Sample Output
1193
1009
9221
3191

1193
1021
9029
3911

……

9173
1559
3821
3391

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-29 01:26
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    # generate all possible permutations for each number in the range [1, 9]
    perms <- lapply(1:9, function(x) {
      perm <- sample(1:9, size = x)
      return(c(rep(perm[1], x), rep(perm[2:(x+1)], 9-x)))
    })
    
    # map each permutation to its corresponding digit in the matrix
    digits <- apply(perms, 1, function(x) paste(x, collapse = ""))
    matrixes <- expand.grid(digits)
    
    # sort matrixes by row and column values
    sorted_matrixes <- matrixes %>% arrange(rowSums, colSums)
    
    # write sorted matrixes to file
    write.table(sorted_matrixes, file = "output.txt", sep = "\n", quote = FALSE, row.names = FALSE, col.names = FALSE)
    

    这段代码使用了 lapply 函数来生成每个数字的可能排列。然后,我们使用 expand.grid 将这些排列组合起来,并将它们映射到相应的数字上。最后,我们将排序后的矩阵写入文件中。

    注意:这个代码没有处理一些特殊情况,例如当两个数字相等时,它们应该被分别放在一行和一列上。此外,它也没有考虑数字的顺序,而是按照它们在矩阵中的位置进行排序。

    评论

报告相同问题?