java - 将字符打印为矩阵

标签 java for-loop matrix

下面的问题有一个字符列表和列数作为输入。列数不是恒定的,并且可能随每个输入而变化。 输出应完全占用除最后一行之外的所有行。

list: a b c d e f g
colums: 3

Wrong:
a b c
d e f
g

Wrong:
a d g
b e
c f

Correct:
a d f
b e g
c

我尝试过以下方法:

public static void printPatern(List<Character> list, int cols) {

    for (int i = 0; i < cols; i++) {

        for (int j = i; j < list.size(); j += cols) {
            System.out.print(list.get(j));

        }
        System.out.println();
    }
}

它给出的输出为(这是错误的):

a d g
b e
c f

我正在尝试使用一种算法来打印正确的输出。我想知道解决这个问题有哪些不同的方法。时间和空间复杂性并不重要。另外,我尝试的上述方法是错误的,因为它以列作为参数,但实际上充当行数。

仅供引用:这不是家庭作业问题。

最佳答案

终于能够设计出这个问题的算法了 请引用下面相同的java代码

 public class puzzle{
        public static void main(String[] args){

            String list[] = { "a", "b", "c","d","e","f","g","h","i","j" };
            int column = 3;

            int rows = list.length/column; //Calculate total full rows
            int lastRowElement = list.length%column;//identify number of elements in last row
            if(lastRowElement >0){
                rows++;//add inclomplete row to total number of full filled rows
            }
            //Iterate over rows
             for (int i = 0; i < rows; i++) {
                int j=i;
                int columnIndex = 1;
                while(j < list.length && columnIndex <=column ){
                    System.out.print("\t"+list[j]);
                    if(columnIndex<=lastRowElement){
                        if(i==rows-1 && columnIndex==lastRowElement){
                            j=list.length; //for last row display nothing after column index reaches to number of elements in last row
                        }else{
                            j += rows; //for other rows if columnIndex is less than or equal to number of elements in last row then add j value by number of rows
                        }

                    }else {
                       if(lastRowElement==0){
                          j += rows;
                       }else{
                        j += rows-1; //for column greater than number of element in last row add j = row-1 as last row will not having the column for this column index.
                       }
                    }

                    columnIndex++;//Increase column Index by 1;
                }

                System.out.println();
                }
        }
    }

关于java - 将字符打印为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43110087/

相关文章:

ruby - 如何从 ruby​​ 中的矩阵中提取子矩阵

matrix - 解决错误类型参数 'cell'

java - ZeroMQ,我们可以使用 inproc : transport along with pub/sub messaging pattern

java - 其余错误代码/成功代码

java - Java中嵌套最深的循环的计数器在哪里声明?

javascript - 为什么不修改字符串的每个字符?

PHP逆时针旋转矩阵

java - 由于 appcompat v7,R.java 没有生成?

Java帮助框架图标

java - 有人可以解释这个方法是如何工作的吗?