Search code examples
javalistsortingreadfileline-breaks

Java algorithm sort after every x line tab to new column


I have a.txt file with 400 lines, I need that every 100th line in the sequence it breaks into a new column, so I'd have 4 columns of 100 in a sequence.

The sequence i want is something like: 1->101->201->301 next line: 2->102->202-> etc... Instead im getting 1->2->3->4 next line: 5->6->7->8

The y represents another sequence that I'm working at the same time, where I want to space at every 6 lines read.

Here's my code so far:

    int x = 0;
    int y = 0;
    int z = 0;      

    int xfinal = 100;
    int yfinal = 6;
    int zfinal = 4;
    int fim= (xfinal*zfinal)+1;

    PrintWriter output = new PrintWriter("C:\\path\\file.txt");

    try {
        for (x = 0; x < xfinal; x++){
          for (y = 0; y < yfinal; y++){
            for (z = 0; z < zfinal; z++) {

                    int pos = (zfinal * yfinal) * x + (zfinal * y) + z;
                    if (pos >= fim) {
                        output.print("\t");
                        continue;
                    }
                    output.print(lines.get(pos) + "\t");
             }
                output.print("\r\n");
          }
            output.print("\r\n");
        }    
    } catch(Exception e) {
        e.printStackTrace();
    }

I've been going around this for quite a while and can't understand how to get the order right since I'm new to java.


Solution

  • you will need something like this (assume lines is the array with all a.txt lines):

        //read file a.txt into the array lines
        String lines[] = raedFileIntoArray("a.txt");
    
        int numberOfLines = lines.length;
        int numberOfCols = 4;
    
        int maxNumOfLines = numberOfLines / numberOfCols;
    
        for (int row = 0; row < maxNumOfLines; ++row) {
            for (int col = 0; col < numberOfCols; ++col) {
                System.out.print(lines[maxNumOfLines * col + row]);
                if (col + 1 < numberOfCols)
                      System.out.print("\t");
            }
            System.out.print("\n");
        }