c# - 将 switch 语句转换为更优雅的解决方案

标签 c# matrix switch-statement

我有一个 9 x 9 矩阵。 (想想数独)。

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

现在我想获得一个“象限”。例如(根据我的代码)象限 2 , 2 返回以下内容:

    5 4 4 
    2 8 1 
    6 4 7 

如果您注意到了,这是从 9 x 9 正中心开始的矩阵。如果您明白我的意思,我已将所有内容分成一对“3”。第一个“ROW”是 0 - 3,第二个是 3 - 6,第三个是 6 - 9..我希望这是有道理的(我愿意接受其他方式关于这个)

无论如何,这是我的代码。我真的不喜欢这种方式,即使它有效。我确实想要速度,因为我正在制作数独求解器。

    //a quadrant returns the mini 3 x 3
    //row 1  has three quads,"1", "2", 3"
    //row 2  has three quads "1", "2", "3" etc
    public int[,] GetQuadrant(int rnum, int qnum) {
        int[,] returnMatrix = new int[3, 3];
        int colBegin, colEnd, rowBegin, rowEnd, row, column;

        //this is so we can keep track of the new matrix
        row = 0;
        column = 0;      
        switch (qnum) {
            case 1:
                colBegin = 0;
                colEnd = 3;
                break;
            case 2:
                colBegin = 3;
                colEnd = 6;
                break;
            case 3:
                colBegin = 6;
                colEnd = 9;
                break;
            default:
                colBegin  = 0;
                colEnd = 0;
                break;
        }

        switch (rnum) {
            case 1:
                rowBegin = 0;
                rowEnd = 3;
                break;
            case 2:
                rowBegin = 3;
                rowEnd = 6;
                break;
            case 3:
                rowBegin = 6;
                rowEnd = 9;
                break;
            default:  
                rowBegin = 0;
                rowEnd = 0;
                break;
        }
        for (int i = rowBegin ; i < rowEnd; i++) {
            for (int j = colBegin; j < colEnd; j++) {                 
                returnMatrix[row, column] = _matrix[i, j];
                column++;
            }
            column = 0;
            row++;
        }
        return returnMatrix;
    }

最佳答案

除非我遗漏了什么,否则为什么不做数学呢?拳头,只存rowBegincolBegin .

现在,简单地发出:

rowBegin = (rnum-1)*3
colBegin = (qnum-1)*3

这映射 1 -> 0、2 -> 3 和 3-> 6。

现在,您从 colBegin 开始循环至 colBegin + 3 , 和 rowBeginrowBegin + 3 .你的默认行为真的有必要吗?如果是,特殊情况 rnum < 1 || rnum > 3qnum < 1 || qnum > 3

关于c# - 将 switch 语句转换为更优雅的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2481565/

相关文章:

c# - Java/C# 静态类之间的主要区别是什么?

c# - 在 asp.net mvc 中没有删除 header 服务器

python - interp2(V,k) 从 Matlab 到 Python

java - 矩阵交换行 - Java

java - 在我的形状计算器 Java 程序中使用带有 Switch/Case 语句的循环

c# - 实体不会从 Azure 表中删除

algorithm - 获取二维数组中的相邻元素?

c++ - switch 语句未执行

java - Android 垂直开关小部件

c# - 开发支持多个数据库的应用程序