逐列打印参差不齐的数组 [英] Printing ragged array column by column

查看:153
本文介绍了逐列打印参差不齐的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出具有不同长度的行的整数数组,是否可以打印整个二维数组,但可以逐列打印?我知道如何逐行执行此操作,但是我为此感到吃力。

Given an array of integers with rows of different lengths, is it possible to print the whole two-dimensional array but doing so column by column? I understand how to do it row by row but I am struggling with this.

int[][] a = new int[5][];

a[0] = new int[4];
a[1] = new int[2];
a[2] = new int[5];
a[3] = new int[3];
a[4] = new int[1];

int longestRowLength = a[0].length;
for(i = 1; i < a.length; i++)
{
    if(a[i].length > longestRowLength)
        longestRowLength = a[i].length;
}

for(i = 0; i < a.length; i++)
{
    for(j = 0; j < a[i].length; j++)
    {
        a[i][j] = rand.nextInt(10);
        System.out.print(a[i][j]);
    }
    System.out.println();
}

for(j = 0; j < longestRowLength; j++)
{
    for(i = 0; i < a.length; i++)
    {
        if(a[i].length < longestRowLength)
            continue;
        System.out.print(a[i][j]);
    }
}
}

我已经做到了,但是问题在于如何识别我们正在超越数组之一。我的if(a [i] .length< longestRowLength不起作用,因为如果它的长度不是最长的,它甚至不会打印任何数字。我该如何实现?

I have done this but the issue is with how to recognize we are going out of bounds with one of the arrays. My if(a[i].length < longestRowLength doesn't work as it will not even print any numbers if its length is not the longest ones. How can I achieve this?

编辑:

好,我将该行更改为:

        if(longestRowLength - a[i].length > 0 && (j+1) > a[i].length)
            continue;
        System.out.print(a[i][j]);

现在它可以工作,但会将列打印为行。无论如何,要使其按列打印但要使其像行一样打印呢(请注意,if语句的第一个条件是不必要的)。

Now it works but it prints the columns as rows. Is there anyway to make it print column by column but to make it print just like it would with rows? (P.S. yeah the first condition of the if statement is unecessary).

推荐答案

用以下代码替换最后一个循环:

Replace your last loop with:

for(j = 0; j < longestRowLength; j++)
{
    for(i = 0; i < a.length; i++)
    {
        if(a[i].length <= j)
            continue;
        System.out.print(a[i][j]);
    }
    System.out.println();
}

逐列打印列。

而不是:

        if(a[i].length <= j)
            continue;

您可以执行以下操作:

        if(a[i].length <= j) {
            System.out.print(' ');
            continue;
        }

为太短的数组留出空间。这样,您可以打印转置的锯齿状矩阵。

to leave a space for arrays which are too short. This way you print the transposed "jagged" matrix.

这篇关于逐列打印参差不齐的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆