Task: Align columns





Java: import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;


public class ColumnAligner {
    private List<String[]> words = new ArrayList<>();
    private int columns = 0;
    private List<Integer> columnWidths = new ArrayList<>();

    
    public ColumnAligner(String s) {
        String[] lines = s.split("\\n");
        for (String line : lines) {
            processInputLine(line);
        }
    }

    
    public ColumnAligner(List<String> lines) {
        for (String line : lines) {
            processInputLine(line);
        }
    }

    private void processInputLine(String line) {
        String[] lineWords = line.split("\\$");
        words.add(lineWords);
        columns = Math.max(columns, lineWords.length);
        for (int i = 0; i < lineWords.length; i++) {
            String word = lineWords[i];
            if (i >= columnWidths.size()) {
                columnWidths.add(word.length());
            } else {
                columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));
            }
        }
    }

    interface AlignFunction {
        String align(String s, int length);
    }

    
    public String alignLeft() {
        return align(new AlignFunction() {
            @Override
            public String align(String s, int length) {
                return StringUtils.rightPad(s, length);
            }
        });
    }

    
    public String alignRight() {
        return align(new AlignFunction() {
            @Override
            public String align(String s, int length) {
                return StringUtils.leftPad(s, length);
            }
        });
    }

    
    public String alignCenter() {
        return align(new AlignFunction() {
            @Override
            public String align(String s, int length) {
                return StringUtils.center(s, length);
            }
        });
    }

    private String align(AlignFunction a) {
        StringBuilder result = new StringBuilder();
        for (String[] lineWords : words) {
            for (int i = 0; i < lineWords.length; i++) {
                String word = lineWords[i];
                if (i == 0) {
                    result.append("|");
                }
                result.append(a.align(word, columnWidths.get(i)) + "|");
            }
            result.append("\n");
        }
        return result.toString();
    }

    public static void main(String args[]) throws IOException {
        if (args.length < 1) {
            System.out.println("Usage: ColumnAligner file [left|right|center]");
            return;
        }
        String filePath = args[0];
        String alignment = "left";
        if (args.length >= 2) {
            alignment = args[1];
        }
        ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));
        switch (alignment) {
        case "left":
            System.out.print(ca.alignLeft());
            break;
        case "right":
            System.out.print(ca.alignRight());
            break;
        case "center":
            System.out.print(ca.alignCenter());
            break;
        default:
            System.err.println(String.format("Error! Unknown alignment: '%s'", alignment));
            break;
        }
    }
}






Fortran:       SUBROUTINE RAKE(IN,M,X,WAY)	
Collates column widths so that each column is wide enough for its widest member.
       INTEGER IN		
       INTEGER M		
       CHARACTER*1 X		
       INTEGER WAY		
       INTEGER W(M + 1)		
       INTEGER C(0:M + 1)	
       CHARACTER*(M) ACARD	
       CHARACTER*(28 + 4*M) FORMAT	
       INTEGER I		
       INTEGER L,LF		
       INTEGER NF,MF		
       CHARACTER*6 WAYNESS(-1:+1)	
       PARAMETER (WAYNESS = (/"Left","Centre","Right"/))	
       INTEGER LINPR	
       COMMON LINPR	
        W = 0		
        MF = 0		
        C(0) = 0	
        WRITE (LINPR,*)	
        WRITE (LINPR,*) "Align ",WAYNESS(MIN(MAX(WAY,-1),+1))	

Chase through the file assessing the lengths of each field.
   10   READ (IN,11,END = 20) L,ACARD(1:L)	
   11   FORMAT (Q,A)				
        CALL LIZZIEBORDEN	
        W(1:NF) = MAX(W(1:NF),C(1:NF) - C(0:NF - 1) - 1)	
        MF = MAX(MF,NF)		
        GO TO 10		

Concoct a FORMAT based on the maximum size of each field. Plus one.
   20   REWIND(IN)		
        WRITE (FORMAT,21) W(1:MF) + 1	
   21   FORMAT ("(",<MF>("A",I0,","))	
        LF = INDEX(FORMAT,", ")		
        IF (LF.LE.0) STOP "Format trouble
        FORMAT(LF:LF) = ")"			
        WRITE (LINPR,*) "Format",FORMAT(1:LF)	

Chug afresh, this time knowing the maximum length of each field.
   30   READ (IN,11,END = 40) L,ACARD(1:L)	
        CALL LIZZIEBORDEN		
        SELECT CASE(WAY)	
         CASE(-1)		
          WRITE (LINPR,FORMAT) (ACARD(C(I - 1) + 1:C(I) - 1)//	
     1     REPEAT(" ",W(I) - C(I) + C(I - 1) + 1),I = 1,NF)	
         CASE( 0)		
          WRITE (LINPR,FORMAT) (ACARD(C(I - 1) + 1:C(I) - 1)//	
     1     REPEAT(" ",(W(I) - C(I) + C(I - 1) + 1)/2),I = 1,NF)	
         CASE(+1)		
          WRITE (LINPR,FORMAT) (ACARD(C(I - 1) + 1:C(I) - 1),I = 1,NF)	
         CASE DEFAULT		
         WRITE (LINPR,*) "Huh? WAY=",WAY	
         STOP "Unanticipated value for WAY
        END SELECT		
        GO TO 30		
Closedown
   40   REWIND(IN)		
       CONTAINS	
        SUBROUTINE LIZZIEBORDEN	
          NF = 0		
          DO I = 1,L		
            IF (ICHAR(ACARD(I:I)).EQ.ICHAR(X)) THEN	
              NF = NF + 1		
              C(NF) = I		
            END IF		
          END DO		
          NF = NF + 1		
          C(NF) = L + 1		
        END SUBROUTINE LIZZIEBORDEN	
      END SUBROUTINE RAKE	

      INTEGER L,M,N	
      INTEGER LINPR,IN	
      COMMON LINPR	
      LINPR = 6		
      IN = 10		
      OPEN (IN,FILE="Rake.txt",STATUS="OLD",ACTION="READ")	
      N = 0		
      M = 0		

    1 READ (IN,2,END = 10) L	
    2 FORMAT (Q)	
      N = N + 1		
      M = MAX(M,L)	
      GO TO 1		

   10 REWIND (IN)	
      WRITE (LINPR,*) N,"Recs, longest rec. length is ",M
      CALL RAKE(IN,M,"$",-1)	
      CALL RAKE(IN,M,"$", 0)	
      CALL RAKE(IN,M,"$",+1)	
      END