将2d数组从行转换为任何类型的数字块

时间:2017-11-29 14:54:50

标签: java arrays 2d block sudoku

我需要将2d数组中的行和列转换为块。

它适用于任何大小为n*n的矩阵,其中包含原始数组中给出的任何数字。

例如:

{{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9},
{1,2,3,4,5,6,7,8,9}};

变为:

{{1,2,3,1,2,3,1,2,3}
{4,5,6,4,5,6,4,5,6}
{7,8,9,7,8,9,7,8,9}
{1,2,3,1,2,3,1,2,3}
{4,5,6,4,5,6,4,5,6}
{7,8,9,7,8,9,7,8,9}
{1,2,3,1,2,3,1,2,3}
{4,5,6,4,5,6,4,5,6}
{7,8,9,7,8,9,7,8,9}}

每个块行使用的数字量为sqrt(n) - 正如您在上面的示例中所看到的,数组中的每一行包含9个数字,每个块行仅包含其中的3个号。

这是我目前的代码:

public static int[][] blocks(int[][] matrix, int sqrtN) {   
    int[][] blocks = matrix;
    int i = 0;
    int counter = 1;
    while(counter+1<sqrtN){ 
        int n = sqrtN;//"n" will the size of the matrix.
        while(n<blocks.length){ 
            int t = counter;
            int j = 0;
            while(t<blocks.length){
                int k = n;
                if(t==counter & i%n==0 & i>0)
                    j= t-1;
                if(j%sqrtN==0)
                    i = 0;
                while(k==n || k%sqrtN!=0){
                    int temp = blocks[t][i];
                    blocks[t][i] = blocks[j][k];
                    blocks[j][k] = temp;
                    i= i+1;
                    k= k+1; 
                }
                j=j+sqrtN;
                t=t+sqrtN;          
            }
            n= n+sqrtN;
            counter= counter+1;

        }
        i=counter;
    }
    return blocks;
}

0 个答案:

没有答案