将二维数组从行转换为块 [英] convert an 2d array from rows to blocks
本文介绍了将二维数组从行转换为块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我数周内都在尝试使用此代码.我需要将二维数组中的行和列转换为块.它应该适用于大小为 n*n 的任何矩阵.(我已经获得了数组的大小)例如:这个:
I am trying to work in this code for weeks. I need to convert rows and columns in a 2d array to blocks. it should work on any matrix in size n*n. (that I have been given the size of the array) for example: this:
int[][] input = {{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}} ;
this is need to be the output:
{{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}}
我总是卡在某个点上.
这是我写的代码:
sqrtN is the size.
在上面提到的情况下,这里的sqrtN是3.
in the case that mentioned above, the sqrtN here is 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;`
我真的很高兴能找到问题的答案.
I will really be glad to find the answer the problem.
谢谢各位.
推荐答案
无需执行复杂的逻辑.尝试使用:
No Need to perform a complex logic. Try to use :
public static int[][] blocks(int[][] matrix, int sqrtN) {
int[][] blocks = matrix;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++){
blocks[i][j] = (i % sqrtN * sqrtN) + (j % sqrtN + 1) ;
}
}
return blocks;
}
这篇关于将二维数组从行转换为块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文