简体   繁体   English

将一维数组打印为两个二维数组

[英]Printing a one dimensional array as a two dimensinoal array

I'm trying to create a method that takes a one dimensional array and prints it out as a two dimensional array, but as square as possible so it looks nice. 我正在尝试创建一种方法,该方法采用一维数组并将其打印为二维数组,但要尽可能方形,这样看起来就很好。 I've tried creating for loops to do this, but how would you figure out how many rows and columns there are? 我尝试创建for循环来执行此操作,但是您如何确定有多少行和列呢? Could someone give me the logic in how to make one, so I can use that to create my own? 有人可以给我做一个的逻辑,以便我可以用它来创建自己的逻辑吗? An explanation would be lovely. 一个解释会很可爱。

This will make a new array that is square and big enough to house all the elements of the old array. 这将形成一个新的正方形数组,其大小足以容纳旧数组的所有元素。 It takes the square root of the original array's length and rounds up. 它取原始数组长度的平方根并四舍五入。

int size = (int)Math.ceil(Math.sqrt(oldArray.length));
int[][]newArray = new int[size][size];

Example: 例:

array =    |1 2 3|
           |4 5 6|
           |7 8 9| (3*3)

Make a 1D array 制作一维数组

int array1 = new int[3*3];

Or you can get length of the array 或者你可以得到array长度

For row length: int row = array.length; 对于行长度: int row = array.length;

For column length: int column = array[0].length; 对于列长度: int column = array[0].length;

and then int array1 = new int[row*column]; 然后int array1 = new int[row*column];

Now iterate over array and copy all elements of array into array1 . 现在遍历array和所有元素复制arrayarray1

         _________________
array1 = |1|2|3|4|5|6|7|8|9|

Now don't ask me for code. 现在不要问我代码。

This method will print the elements in your one-dimensional array as close as possible to a square pattern on the console output. 此方法将一维数组中的元素打印到尽可能接近控制台输出的正方形图案的位置。 It places tabs in between elements to line them up on each row. 它将制表符放在元素之间,以将它们在每一行上对齐。

private void printMyArray(String[]  onDimensionalArray) {
    int cols = (int) Math.floor(Math.sqrt(onDimensionalArray.length));
    int currentCol = 0;
    for(String element : onDimensionalArray) {
        System.out.print(element + "\t");
        if(currentCol >= cols) {
            System.out.println("");
            currentCol = 0;
        }
        else {
            currentCol++;
        }
    }
}

check this out 看一下这个

int array2d[][] = new int[10][3];


for(int i=0; i<10;i++)
for(int j=0;j<3;j++)
   array2d[i][j] = array1d[(j*10) + i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM