Align columns: Difference between revisions
Added XPL0 example.
(→{{header|Haskell}}: Or, using Text and its functions as an alternative to [Char]) |
(Added XPL0 example.) |
||
(120 intermediate revisions by 51 users not shown) | |||
Line 14:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.</pre>
Note that:
# The example input texts lines may, or may not, have trailing dollar characters.
# All columns should share the same alignment.
# Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
# Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.
# The minimum space between columns should be computed from the text and not hard-coded.
# It is ''not'' a requirement to add separating characters between or around columns.
{{Template:Strings}}
<br><br>
=={{header|11l}}==
{{trans|D}}
<syntaxhighlight lang="11l">V txt = ‘Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.’
V parts = txt.split("\n").map(line -> line.rtrim(‘$’).split(‘$’))
V max_widths = [0] * parts[0].len
L(line) parts
L(word) line
max_widths[L.index] = max(max_widths[L.index], word.len)
((String, Int) -> String) ljust = (s, w) -> s‘’(‘ ’ * (w - s.len))
((String, Int) -> String) centr = (s, w) -> (‘ ’ * (w - s.len - (w I/ 2 - s.len I/ 2)))‘’s‘’(‘ ’ * (w I/ 2 - s.len I/ 2))
((String, Int) -> String) rjust = (s, w) -> (‘ ’ * (w - s.len))‘’s
L(justify) [ljust, centr, rjust]
print([‘Left’, ‘Center’, ‘Right’][L.index]‘ column-aligned output:’)
L(line) parts
L(word) line
print(justify(word, max_widths[L.index]), end' ‘ ’)
print()
print(‘- ’ * 52)</syntaxhighlight>
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Align columns 12/04/2019
ALICOL CSECT
USING ALICOL,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R8,1 i=1
DO WHILE=(C,R8,LE,=A(NI)) do r=1 to hbound(t)
LA R7,1 j=1
LA R6,L'T i=length(t)
DO WHILE=(C,R6,GE,=A(1)) do i=length(t) to 1 by -1
LR R1,R8 r
MH R1,=AL2(L'T) ~
LA R4,T-L'T(R1) t(r)
BCTR R4,0 -1
AR R4,R6 +i
MVC CI,0(R4) ci=substr(t(r),i,1)
CLI CI,C' ' if ci=' '
BE ITERI1 then iterate i
CLI CI,C'$' if ci='$'
BE ITERI1 then iterate i
LR R7,R6 j=i
B LEAVEI1 leave i
ITERI1 BCTR R6,0 i--
ENDDO , enddo i
LEAVEI1 LR R1,R8 r
MH R1,=AL2(L'T) ~
LA R4,T-L'T(R1) @t(r)
LA R2,WT @wt
LR R5,R7 j
ICM R5,B'1000',=C' ' padding
LA R3,L'T length(wt)
MVCL R2,R4 wt=substr(t(r),1,j)
LA R0,1 1
ST R0,I0 i0=1
SR R9,R9 c=0
LA R6,1 i=1
DO WHILE=(CR,R6,LE,R7) do i=1 to j
LA R4,WT-1 @wt
AR R4,R6 i
MVC CI(1),0(R4) ci=substr(wt,i,1)
IF CLI,CI,EQ,C'$' THEN if ci='$' then
BAL R14,SEQ call seq
LR R2,R6 i
LA R2,1(R2) +1
ST R2,I0 i0=i+1
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
BAL R14,SEQ call seq
IF C,R9,GT,COLS THEN if c>cols then
ST R9,COLS cols=c
ENDIF , endif
LA R8,1(R8) r++
ENDDO , enddo r
LR R2,R8 r
BCTR R2,0 -1
ST R2,ROWS rows=r-1
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(3)) do j=1 to 3
XPRNT =C'--',2 print
LA R8,1 r=1
DO WHILE=(C,R8,LE,ROWS) do r=1 to rows
MVC PG,=CL120' ' pg=' '
LA R0,1 1
ST R0,IB ib=1
LA R9,1 c=1
DO WHILE=(C,R9,LE,COLS) do c=1 to cols
LR R1,R8 r
BCTR R1,0 -1
MH R1,=AL2(NJ) ~
AR R1,R9 c
MH R1,=AL2(L'WOR) ~
LA R4,WOR-L'WOR(R1) @wor(r,c)
MVC W,0(R4) w=wor(r,c)
LA R6,L'W i=length(w)
DO WHILE=(C,R6,GE,=A(1)) do i=length(w) to 1 by -1
LA R4,W-1 @w
AR R4,R6 i
MVC CI,0(R4) ci=substr(w,i,1)
CLI CI,C' ' if ci^=' '
BNE LEAVEI2 then goto leavei2;
BCTR R6,0 i--
ENDDO , enddo i
LEAVEI2 EQU * ~
IF LTR,R6,Z,R6 THEN if i=0 then
LA R10,1 l=1
ELSE , else
LR R10,R6 l=i
ENDIF , endif
IF C,R7,EQ,=F'1' THEN if j=1 then
L R11,IB ibx=ib
ENDIF , endif
IF C,R7,EQ,=F'2' THEN if j=2 then
LR R1,R9 c
SLA R1,2 ~
L R11,WID-L'WID(R1) wid(c)
A R11,IB +ib
SR R11,R10 ibx=ib+wid(c)-l
ENDIF , endif
IF C,R7,EQ,=F'3' THEN if j=3 then
LR R1,R9 c
SLA R1,2 ~
L R11,WID-L'WID(R1) wid(c)
SR R11,R10 -l
SRA R11,1 /2
A R11,IB ibx=ib+(wid(c)-l)/2
ENDIF , endif
LA R2,PG-1 @pg
AR R2,R11 +ibx
LR R3,R10 l
LA R4,W @w
LR R5,R10 l
MVCL R2,R4 substr(pg,ibx,l)=substr(w,1,l)
LR R1,R9 c
SLA R1,2 ~
L R2,WID-L'WID(R1) wid(c)
A R2,IB +ib
LA R2,1(R2) +1
ST R2,IB ib=ib+wid(c)+1
LA R9,1(R9) c++
ENDDO , enddo c
XPRNT PG,L'PG print
LA R8,1(R8) r++
ENDDO , enddo r
LA R7,1(R7) j++
ENDDO , enddo j
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
SEQ EQU * --begin seq
LA R9,1(R9) c=c+1
LR R10,R6 i
S R10,I0 l=i-i0
LA R4,WT-1 @wt
A R4,I0 +i0
LR R5,R10 l
ICM R5,B'1000',=C' ' padding
LR R1,R8 r
BCTR R1,0 -1
MH R1,=AL2(NJ) ~
AR R1,R9 +c
MH R1,=AL2(L'WOR) ~
LA R2,WOR-L'WOR(R1) @wor(r,c)
LA R3,L'WOR length(wor)
MVCL R2,R4 wor(r,c)=substr(wt,i0,l)
LR R1,R9 c
SLA R1,2 ~
L R2,WID-L'WID(R1) wid(c)
IF CR,R2,LT,R10 THEN if l>wid(c) then
LR R1,R9 c
SLA R1,2 ~
ST R10,WID-L'WID(R1) wid(c)=l
ENDIF , endif
BR R14 --end seq
NI EQU 6 ni
NJ EQU 12 nj
T DC CL68'Given$a$text$file$of$many$lines,$where$fields$within$a$line$'
DC CL68'are$delineated$by$a$single$''dollar''$character,$write$a$progX
ramm'
DC CL68'that$aligns$each$column$of$fields$by$ensuring$that$words$in$eX
ach$'
DC CL68'column$are$separated$by$at$least$one$space.'
DC CL68'Further,$allow$for$each$word$in$a$column$to$be$either$left$'
DC CL68'justified,$right$justified,$or$center$justified$within$its$coX
lumn.'
WOR DC (NI*NJ)CL10' ' wor(ni,nj) char(10)
WID DC 16F'0' wid(16)
COLS DC F'0'
ROWS DC F'0'
WT DS CL(L'T)
W DS CL(L'WOR)
CI DS CL1
I0 DS F
IB DS F
PG DS CL120
REGEQU
END ALICOL </syntaxhighlight>
{{out}}
<pre>
--
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a programm
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
--
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a programm
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
--
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a programm
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|8th}}==
<syntaxhighlight lang="forth">
quote | Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 70 ⟶ 308:
bye ;
</syntaxhighlight>
{{out}}
<pre>
Line 96 ⟶ 334:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program alignColumn64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 16 * 10
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLeft: .asciz "LEFT :\n"
szMessRight: .asciz "\nRIGHT :\n"
szMessCenter: .asciz "\nCENTER :\n"
szCarriageReturn: .asciz "\n"
szLine1: .asciz "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
szLine2: .asciz "are$delineated$by$a$single$'dollar'$character,$write$a$program"
szLine3: .asciz "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
szLine4: .asciz "column$are$separated$by$at$least$one$space."
szLine5: .asciz "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
szLine6: .asciz "justified,$right$justified,$or$center$justified$within$its$column."
.align 8
qtbPtLine: .quad szLine1,szLine2,szLine3,szLine4,szLine5,szLine6
.equ NBLINES, (. - qtbPtLine) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrqtbPtLine
bl computeMaxiLengthWords
mov x19,x0 // column counter
ldr x0,qAdrszMessLeft
bl affichageMess
ldr x0,qAdrqtbPtLine
mov x1,x19 // column size
bl alignLeft
ldr x0,qAdrszMessRight
bl affichageMess
ldr x0,qAdrqtbPtLine
mov x1,x19 // column size
bl alignRight
ldr x0,qAdrszMessCenter
bl affichageMess
ldr x0,qAdrqtbPtLine
mov x1,x19 // column size
bl alignCenter
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessLeft: .quad szMessLeft
qAdrszMessRight: .quad szMessRight
qAdrszMessCenter: .quad szMessCenter
qAdrqtbPtLine: .quad qtbPtLine
/******************************************************************/
/* compute maxi words */
/******************************************************************/
/* x0 contains adresse pointer array */
computeMaxiLengthWords:
stp fp,lr,[sp,-16]! // save registres
mov x2,#0 // indice pointer array
mov x3,#0 // maxi length words
1:
ldr x1,[x0,x2,lsl #3] // load pointer
mov x4,#0 // length words counter
mov x5,#0 // indice line character
2:
ldrb w6,[x1,x5] // load a line character
cmp x6,#0 // line end ?
beq 4f
cmp x6,#'$' // separator ?
bne 3f
cmp x4,x3
csel x3,x4,x3,gt // if greather replace maxi
mov x4,#-1 // raz length counter
3:
add x4,x4,#1
add x5,x5,#1 // increment character indice
b 2b // and loop
4: // end line
cmp x4,x3 // compare word counter and maxi
csel x3,x4,x3,gt // if greather replace maxi
add x2,x2,#1 // increment indice line pointer
cmp x2,#NBLINES // maxi ?
blt 1b // no -> loop
mov x0,x3 // return maxi length counter
100:
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* align left */
/******************************************************************/
/* x0 contains the address of pointer array*/
/* x1 contains column size */
alignLeft:
stp fp,lr,[sp,-16]! // save registres
sub sp,sp,#BUFFERSIZE // reserve place for output buffer
mov fp,sp
mov x5,x0 // array address
mov x2,#0 // indice array
1:
ldr x3,[x5,x2,lsl #3] // load line pointer
mov x4,#0 // line character indice
mov x7,#0 // output buffer character indice
mov x6,#0 // word lenght
2:
ldrb w0,[x3,x4] // load a character line
strb w0,[fp,x7] // store in buffer
cmp w0,#0 // line end ?
beq 6f
cmp w0,#'$' // separator ?
bne 5f
mov x0,#' '
strb w0,[fp,x7] // replace $ by space
3:
cmp x6,x1 // length word >= length column
bge 4f
add x7,x7,#1
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x6,x6,#1
b 3b // and loop
4:
mov x6,#-1 // raz word length
5:
add x4,x4,#1 // increment line indice
add x7,x7,#1 // increment buffer indice
add x6,x6,#1 // increment word length
b 2b
6:
mov x0,#'\n'
strb w0,[fp,x7] // return line
add x7,x7,#1
mov x0,#0
strb w0,[fp,x7] // final zéro
mov x0,fp
bl affichageMess // display output buffer
add x2,x2,#1
cmp x2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* align right */
/******************************************************************/
/* x0 contains the address of pointer array*/
/* x1 contains column size */
alignRight:
stp fp,lr,[sp,-16]! // save registres
sub sp,sp,#BUFFERSIZE // reserve place for output buffer
mov fp,sp
mov x5,x0 // array address
mov x2,#0 // indice array
1:
ldr x3,[x5,x2,lsl #3] // load line pointer
mov x4,#0 // line character indice
mov x7,#0 // output buffer character indice
mov x6,#0 // word lenght
mov x8,x3 // word begin address
2: // compute word length
ldrb w0,[x3,x4] // load a character line
cmp w0,#0 // line end ?
beq 3f
cmp w0,#'$' // separator ?
beq 3f
add x4,x4,#1 // increment line indice
add x6,x6,#1 // increment word length
b 2b
3:
cmp x6,#0
beq 4f
sub x6,x1,x6 // compute left spaces to add
4: // loop add spaces to buffer
cmp x6,#0
blt 5f
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x7,x7,#1
sub x6,x6,#1
b 4b // and loop
5:
mov x9,#0
6: // copy loop word to buffer
ldrb w0,[x8,x9]
cmp x0,#'$'
beq 7f
cmp x0,#0 // line end
beq 8f
strb w0,[fp,x7]
add x7,x7,#1
add x9,x9,#1
b 6b
7:
add x8,x8,x9
add x8,x8,#1 // new word begin
mov x6,#0 // raz word length
add x4,x4,#1 // increment line indice
b 2b
8:
mov x0,#'\n'
strb w0,[fp,x7] // return line
add x7,x7,#1
mov x0,#0
strb w0,[fp,x7] // final zéro
mov x0,fp
bl affichageMess // display output buffer
add x2,x2,#1
cmp x2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/******************************************************************/
/* align center */
/******************************************************************/
/* x0 contains the address of pointer array*/
/* x1 contains column size */
alignCenter:
stp fp,lr,[sp,-16]! // save registres
sub sp,sp,#BUFFERSIZE // reserve place for output buffer
mov fp,sp
mov x5,x0 // array address
mov x2,#0 // indice array
1:
ldr x3,[x5,x2,lsl #3] // load line pointer
mov x4,#0 // line character indice
mov x7,#0 // output buffer character indice
mov x6,#0 // word length
mov x8,x3 // word begin address
2: // compute word length
ldrb w0,[x3,x4] // load a character line
cmp w0,#0 // line end ?
beq 3f
cmp w0,#'$' // separator ?
beq 3f
add x4,x4,#1 // increment line indice
add x6,x6,#1 // increment word length
b 2b
3:
cmp x6,#0
beq 5f
sub x6,x1,x6 // total spaces number to add
mov x12,x6
lsr x6,x6,#1 // divise by 2 = left spaces number
4:
cmp x6,#0
blt 5f
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x7,x7,#1 // increment output indice
sub x6,x6,#1 // decrement number space
b 4b // and loop
5:
mov x9,#0
6: // copy loop word to buffer
ldrb w0,[x8,x9]
cmp x0,#'$' // séparator ?
beq 7f
cmp x0,#0 // line end ?
beq 10f
strb w0,[fp,x7]
add x7,x7,#1
add x9,x9,#1
b 6b
7:
lsr x6,x12,#1 // divise total spaces by 2
sub x6,x12,x6 // and compute number spaces to right side
8: // loop to add right spaces
cmp x6,#0
ble 9f
mov x0,#' '
strb w0,[fp,x7] // add space to buffer
add x7,x7,#1
sub x6,x6,#1
b 8b // and loop
9:
add x8,x8,x9
add x8,x8,#1 // new address word begin
mov x6,#0 // raz word length
add x4,x4,#1 // increment line indice
b 2b // and loop new word
10:
mov x0,#'\n'
strb w0,[fp,x7] // return line
add x7,x7,#1
mov x0,#0
strb w0,[fp,x7] // final zéro
mov x0,fp
bl affichageMess // display output buffer
add x2,x2,#1 // increment line indice
cmp x2,#NBLINES // maxi ?
blt 1b // loop
100:
add sp,sp,#BUFFERSIZE
ldp fp,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
LEFT :
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
RIGHT :
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
CENTER :
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|ABAP}}==
<
start-of-selection.
Line 174 ⟶ 769:
sy-linno = sy-linno - 1.
endloop.
endform.</
<pre style="height:15ex;overflow:scroll">Given a text file of many lines, where fields within a line
Line 196 ⟶ 791:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|Action!}}==
Atari 8-bit computer is able to show only 40 characters per line. The user has to press left/right arrow keys to scroll the content of whole text.
<syntaxhighlight lang="action!">DEFINE LINES_COUNT="10"
DEFINE COLUMNS_COUNT="20"
DEFINE WORDS_COUNT="100"
DEFINE BUFFER_SIZE="2000"
DEFINE LINE_WIDTH="40"
DEFINE PTR="CARD"
PTR ARRAY lines(LINES_COUNT)
BYTE ARRAY wordStart(WORDS_COUNT)
BYTE ARRAY wordLen(WORDS_COUNT)
BYTE ARRAY firstWordInLine(LINES_COUNT)
BYTE ARRAY wordsInLine(LINES_COUNT)
BYTE ARRAY colWidths(COLUMNS_COUNT)
BYTE ARRAY buffer(BUFFER_SIZE)
BYTE lineCount,colCount,wordCount
CHAR sep=['$]
PROC AddLine(CHAR ARRAY line)
lines(lineCount)=line
lineCount==+1
RETURN
PROC InitData()
lineCount=0
AddLine("Given$a$text$file$of$many$lines,$where$fields$within$a$line$")
AddLine("are$delineated$by$a$single$'dollar'$character,$write$a$program")
AddLine("that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$")
AddLine("column$are$separated$by$at$least$one$space.")
AddLine("Further,$allow$for$each$word$in$a$column$to$be$either$left$")
AddLine("justified,$right$justified,$or$center$justified$within$its$column.")
RETURN
PROC ProcessData()
BYTE i,pos,len,start,w,col
CHAR ARRAY line
colCount=0 wordCount=0
FOR i=0 TO lineCount-1
DO
line=lines(i)
len=line(0)
firstWordInLine(i)=wordCount
wordsInLine(i)=0
pos=1 col=0
WHILE pos<=len
DO
start=pos
WHILE pos<=len AND line(pos)#sep
DO pos==+1 OD
w=pos-start
wordStart(wordCount)=start
wordLen(wordCount)=w
wordCount==+1
wordsInLine(i)==+1
IF col=colCount THEN
colWidths(col)=w
colCount==+1
ELSEIF w>colWidths(col) THEN
colWidths(col)=w
FI
col==+1
pos==+1
OD
OD
RETURN
BYTE FUNC GetBufLineLength()
BYTE i,res
res=0
FOR i=0 TO colCount-1
DO
res==+colWidths(i)+1
OD
res==+1
RETURN (res)
BYTE FUNC AtasciiToInternal(CHAR c)
BYTE c2
c2=c&$7F
IF c2<32 THEN
RETURN (c+64)
ELSEIF c2<96 THEN
RETURN (c-32)
FI
RETURN (c)
PROC GenerateLine(BYTE index BYTE align BYTE POINTER p)
BYTE wordIndex,last,left,right,start,len,colW
INT i,j
CHAR ARRAY line
line=lines(index)
wordIndex=firstWordInLine(index)
last=wordIndex+wordsInLine(index)-1
FOR i=0 TO colCount-1
DO
colW=colWidths(i)
p^=124 p==+1
IF wordIndex<=last THEN
start=wordStart(wordIndex)
len=wordLen(wordIndex)
IF align=0 THEN
left=0
right=colW-len
ELSEIF align=1 THEN
left=(colW-len)/2
right=colW-left-len
ELSE
left=colW-len
right=0
FI
p==+left
for j=start TO start+len-1
DO
p^=AtasciiToInternal(line(j))
p==+1
OD
p==+right
ELSE
p==+colW
FI
wordIndex==+1
OD
p^=124
RETURN
PROC FillBuffer(BYTE lineWidth)
BYTE i,align
BYTE POINTER p
p=buffer
Zero(p,BUFFER_SIZE)
FOR align=0 TO 2
DO
FOR i=0 TO lineCount-1
DO
GenerateLine(i,align,p)
p==+lineWidth
OD
OD
RETURN
BYTE FUNC GetMaxOffset()
BYTE res
res=GetBufLineLength()-LINE_WIDTH
RETURN (res)
PROC Update(BYTE offset,lineWidth)
BYTE POINTER srcPtr,dstPtr
BYTE i
srcPtr=buffer+offset
dstPtr=PeekC(88)+3*LINE_WIDTH
FOR i=0 TO 3*lineCount-1
DO
MoveBlock(dstPtr,srcPtr,LINE_WIDTH)
srcPtr==+lineWidth
dstPtr==+LINE_WIDTH
IF i=lineCount-1 OR i=2*lineCount-1 THEN
dstPtr==+LINE_WIDTH
FI
OD
RETURN
PROC Main()
BYTE
lineWidth,offset,maxOffset,k,
CH=$02FC, ;Internal hardware value for last key pressed
CRSINH=$02F0 ;Controls visibility of cursor
CRSINH=1 ;hide cursor
InitData()
ProcessData()
lineWidth=GetBufLineLength()
FillBuffer(lineWidth)
Position(2,1)
Print("Press left/right arrow key to scroll")
maxOffset=lineWidth-LINE_WIDTH
offset=0
Update(offset,lineWidth)
DO
k=CH
IF k#$FF THEN
CH=$FF
FI
IF k=134 AND offset>0 THEN
offset==-1
Update(offset,lineWidth)
ELSEIF k=135 AND offset<maxOffset THEN
offset==+1
Update(offset,lineWidth)
ELSEIF k=28 THEN
EXIT
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Align_columns.png Screenshot from Atari 8-bit computer]
<pre>
Press left/right arrow key to scroll
|Given |a |text |file |of |many |lines, |where |fields |within |a |line|
|are |delineated|by |a |single|'dollar' |character,|write |a |program| | |
|that |aligns |each |column|of |fields |by |ensuring|that |words |in |each|
|column |are |separated |by |at |least |one |space. | | | | |
|Further, |allow |for |each |word |in |a |column |to |be |either|left|
|justified,|right |justified,|or |center|justified|within |its |column.| | | |
| Given | a | text | file | of | many | lines, | where |fields |within | a |line|
| are |delineated| by | a |single|'dollar' |character,| write | a |program| | |
| that | aligns | each |column| of | fields | by |ensuring| that | words | in |each|
| column | are |separated | by | at | least | one | space. | | | | |
| Further, | allow | for | each | word | in | a | column | to | be |either|left|
|justified,| right |justified,| or |center|justified| within | its |column.| | | |
| Given| a| text| file| of| many| lines,| where| fields| within| a|line|
| are|delineated| by| a|single| 'dollar'|character,| write| a|program| | |
| that| aligns| each|column| of| fields| by|ensuring| that| words| in|each|
| column| are| separated| by| at| least| one| space.| | | | |
| Further,| allow| for| each| word| in| a| column| to| be|either|left|
|justified,| right|justified,| or|center|justified| within| its|column.| | | |
</pre>
=={{header|Ada}}==
{{libheader|Simple components for Ada}}
<
with Ada.Text_IO; use Ada.Text_IO;
with Strings_Edit; use Strings_Edit;
Line 263 ⟶ 1,096:
end loop;
Close (File);
end Column_Aligner;</
Formatted file sample:
<pre style="height:15ex;overflow:scroll">
Line 287 ⟶ 1,120:
=={{header|Aime}}==
<
file f;
text n, t;
list c, r, s;
integer a, i
f.b_affix(b);
m = 0;
while
m = max(m,
}
Line 311 ⟶ 1,145:
while (i < m) {
w = 0;
w = max(w, length(r[i]));
}
}
i += 1;
}
for (k, t in list("left", "center", "right")) {
o_(t, " justified\n");
for (i, n in r) {
o_form("/w~3/~/w~1/", a = (2 - k) * m >> 1, "", m - a, "", n);
}
o_newline();
}
o_newline();
}</
{{Out}}
<pre>left justified
Line 368 ⟶ 1,191:
=={{header|ALGOL 68}}==
<
STRING text in list := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"+nl+
"are$delineated$by$a$single$'dollar'$character,$write$a$program"+nl+
Line 433 ⟶ 1,256:
aligner(page, align OF aligners[index])
OD
END</
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#define IGet(__N__,__X__) [__N__]SGet(__X__)
#include <hbasic.h>
#define MAX_LINE 1000
Begin
Option Stack 15
Declare as Numeric ( fd, i, index, max token )
as Numeric ( num tokens, size Column, tCells )
as Alpha ( line )
as Numeric ( display Left, display Right, display Center )
GetParam(script, file to edit, separator)
// get statistics of file: #lines, #total chars, line more long, and num tokens from first line.
Token Sep( separator )
Stat( file to edit, dats )
// declare arrays to work:
Dim ( IGet(1,dats), Add(IGet(4,dats),10) ) for Fill Array("",cells)
Clear(dats)
MStore ( cells, display Left, display Right, display Center )
// read each line as array, get # of elements, and put into array cells:
Open(OPEN_READ, file to edit ) (fd)
When( File Error ){ Stop }
index=1
While Not Eof(fd)
ReadRow(MAX_LINE)(fd) and Copy to (line); get Length, and Move to (num tokens)
Set Interval [index, 1:num tokens]; Take( line ) and SPut(cells)
When ( var( max token) Is Lt (num tokens) ) { max token = num tokens }
++index
Wend
Close(fd)
// formatting...
For Up( i:=1, max token, 1 )
Set Interval [1:end,i], and Let ( size Column := MaxValue( Len(Get(cells)) ) Plus(1) )
Let ( tCells := Get(cells) )
LPad$( " ", size Column, tCells ), and Put(display Left)
RPad$( " ", size Column, tCells ), and Put(display Right)
CPad$( " ", size Column, tCells ), and Put(display Center)
Next
// display:
Token Sep ("")
Print("Left Pad:\n", display Left, Newl, "Right Pad:\n", display Right, Newl, "Center Pad:\n", display Center,Newl)
End
</syntaxhighlight>
{{out}}
Sample String was saved into "sample.txt" file.
<pre>
$ hopper src/acolumns.bas sample.txt "$"
Left Pad:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Right Pad:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Center Pad:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
$
</pre>
=={{header|APL}}==
<syntaxhighlight lang="apl">align←{
left ← {⍺↑⍵}
right ← {(-⍺)↑⍵}
center ← {⍺↑(-⌊(≢⍵)+(⍺-≢⍵)÷2)↑⍵}
text ← ⊃⎕NGET⍵
words ← ((≠∘'$')⊆⊣)¨(~text∊⎕TC)⊆text
sizes ← 1+⌈⌿↑≢¨¨words
method ← ⍎⍺
↑,/↑(⊂sizes)method¨¨↓↑words
}</syntaxhighlight>
{{out}}
<pre> 'left' align 'test.txt'
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
'center' align 'test.txt'
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
'right' align 'test.txt'
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|AppleScript}}==
Probably not the first language in which you would really choose to do this kind of thing, but certainly possible, and can be
{{trans|JavaScript}}
<syntaxhighlight lang="applescript">-- COLUMN ALIGNMENTS ---------------------------------------------------------
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" & ¬
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" & ¬
Line 453 ⟶ 1,393:
property eCenter : 0
property eRight : 1
-- columnsAligned :: EnumValue -> [[String]] -> String
Line 472 ⟶ 1,398:
-- padwords :: Int -> [String] -> [[String]]
script padwords
on
-- pad :: String -> String
script pad
on
set lngPad to n - (length of str)
if eAlign = my eCenter then
Line 489 ⟶ 1,415:
end if
end if
end
end script
map(pad, lstWords)
end
end script
Line 505 ⟶ 1,431:
-- _words :: Text -> [Text]
script _words
on
splitOn(strColDelim, str)
end
end script
Line 515 ⟶ 1,441:
-- fullRow :: [[a]] -> [[a]]
script fullRow
on
lst & replicate(nCols - (length of lst), {""})
end
end script
Line 525 ⟶ 1,451:
-- widest [a] -> Int
on widest(xs)
|length|(maximumBy(comparing(my |length|), xs))
end widest
-- TEST ----------------------------------------------------------------------
on run
set lstCols to lineColumns("$", pstrLines)
script testAlignment
on |λ|(eAlign)
columnsAligned(eAlign, lstCols)
end |λ|
end script
map(testAlignment, {eLeft, eRight, eCenter}))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- comparing :: (a -> b) -> (a -> a -> Ordering)
on comparing(f)
set mf to mReturn(f)
script
on |λ|(a, b)
set x to mf's |λ|(a)
set
if x < y then
else
if x > y then
1
else
0
end script
end comparing
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 588 ⟶ 1,496:
set lng to length of xs
repeat with i from 1 to lng
set v to
end repeat
return v
end tell
end foldl
-- Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- map :: (a -> b) -> [a] -> [b]
Line 600 ⟶ 1,533:
set lst to {}
repeat with i from 1 to lng
set end of lst to
end repeat
return lst
Line 606 ⟶ 1,539:
end map
--
on
set
script max
on |λ|(a, b)
if a is missing value or cmp's |λ|(a, b) < 0 then
b
else
a
end if
end |λ|
end script
foldl(max, missing value, xs)
end maximumBy
--
on
if
else
end if
end
-- Egyptian multiplication - progressively doubling a list, appending
Line 635 ⟶ 1,570:
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to ""
else
set out to {}
end if
if n < 1 then return out
set dbl to a
Line 647 ⟶ 1,586:
end replicate
-- Text -> Text -> [Text]
on splitOn(strDelim, strMain)
set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
set my text item
end splitOn
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
-- [Text] -> Text
on unlines(lstLines)
intercalate(linefeed, lstLines)
end unlines
-- [Text] -> Text
on unwords(lstWords)
intercalate(" ", lstWords)
end unwords
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre> Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
Line 681 ⟶ 1,653:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. </pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program alignColumn.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ BUFFERSIZE, 20 * 10
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLeft: .asciz "LEFT :\n"
szMessRight: .asciz "\nRIGHT :\n"
szMessCenter: .asciz "\nCENTER :\n"
szCarriageReturn: .asciz "\n"
szLine1: .asciz "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
szLine2: .asciz "are$delineated$by$a$single$'dollar'$character,$write$a$program"
szLine3: .asciz "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
szLine4: .asciz "column$are$separated$by$at$least$one$space."
szLine5: .asciz "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
szLine6: .asciz "justified,$right$justified,$or$center$justified$within$its$column."
itbPtLine: .int szLine1,szLine2,szLine3,szLine4,szLine5,szLine6
.equ NBLINES, (. - itbPtLine) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdritbPtLine
bl computeMaxiLengthWords
mov r10,r0 @ column counter
ldr r0,iAdrszMessLeft
bl affichageMess
ldr r0,iAdritbPtLine
mov r1,r10 @ column size
bl alignLeft
ldr r0,iAdrszMessRight
bl affichageMess
ldr r0,iAdritbPtLine
mov r1,r10 @ column size
bl alignRight
ldr r0,iAdrszMessCenter
bl affichageMess
ldr r0,iAdritbPtLine
mov r1,r10 @ column size
bl alignCenter
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessLeft: .int szMessLeft
iAdrszMessRight: .int szMessRight
iAdrszMessCenter: .int szMessCenter
iAdritbPtLine: .int itbPtLine
/******************************************************************/
/* compute maxi words */
/******************************************************************/
/* r0 contains adresse pointer array */
computeMaxiLengthWords:
push {r1-r6,lr} @ save registers
mov r2,#0 @ indice pointer array
mov r3,#0 @ maxi length words
1:
ldr r1,[r0,r2,lsl #2] @ load pointer
mov r4,#0 @ length words counter
mov r5,#0 @ indice line character
2:
ldrb r6,[r1,r5] @ load a line character
cmp r6,#0 @ line end ?
beq 4f
cmp r6,#'$' @ separator ?
bne 3f
cmp r4,r3
movgt r3,r4 @ ig greather replace maxi
mov r4,#-1 @ raz length counter
3:
add r4,r4,#1
add r5,r5,#1 @ increment character indice
b 2b @ and loop
4: @ end line
cmp r4,r3 @ compare word counter and maxi
movgt r3,r4 @ if greather replace maxi
add r2,r2,#1 @ increment indice line pointer
cmp r2,#NBLINES @ maxi ?
blt 1b @ no -> loop
mov r0,r3 @ return maxi length counter
100:
pop {r1-r6,pc}
/******************************************************************/
/* align left */
/******************************************************************/
/* r0 contains the address of pointer array*/
/* r1 contains column size */
alignLeft:
push {r4-r7,fp,lr} @ save registers
sub sp,sp,#BUFFERSIZE @ reserve place for output buffer
mov fp,sp
mov r5,r0 @ array address
mov r2,#0 @ indice array
1:
ldr r3,[r5,r2,lsl #2] @ load line pointer
mov r4,#0 @ line character indice
mov r7,#0 @ output buffer character indice
mov r6,#0 @ word lenght
2:
ldrb r0,[r3,r4] @ load a character line
strb r0,[fp,r7] @ store in buffer
cmp r0,#0 @ line end ?
beq 6f
cmp r0,#'$' @ separator ?
bne 5f
mov r0,#' '
strb r0,[fp,r7] @ replace $ by space
3:
cmp r6,r1 @ length word >= length column
bge 4f
add r7,r7,#1
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r6,r6,#1
b 3b @ and loop
4:
mov r6,#-1 @ raz word length
5:
add r4,r4,#1 @ increment line indice
add r7,r7,#1 @ increment buffer indice
add r6,r6,#1 @ increment word length
b 2b
6:
mov r0,#'\n'
strb r0,[fp,r7] @ return line
add r7,r7,#1
mov r0,#0
strb r0,[fp,r7] @ final zéro
mov r0,fp
bl affichageMess @ display output buffer
add r2,r2,#1
cmp r2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
pop {r4-r7,fp,pc}
/******************************************************************/
/* align right */
/******************************************************************/
/* r0 contains the address of pointer array*/
/* r1 contains column size */
alignRight:
push {r4-r9,fp,lr} @ save registers
sub sp,sp,#BUFFERSIZE @ reserve place for output buffer
mov fp,sp
mov r5,r0 @ array address
mov r2,#0 @ indice array
1:
ldr r3,[r5,r2,lsl #2] @ load line pointer
mov r4,#0 @ line character indice
mov r7,#0 @ output buffer character indice
mov r6,#0 @ word lenght
mov r8,r3 @ word begin address
2: @ compute word length
ldrb r0,[r3,r4] @ load a character line
cmp r0,#0 @ line end ?
beq 3f
cmp r0,#'$' @ separator ?
beq 3f
add r4,r4,#1 @ increment line indice
add r6,r6,#1 @ increment word length
b 2b
3:
cmp r6,#0
beq 4f
sub r6,r1,r6 @ compute left spaces to add
4: @ loop add spaces to buffer
cmp r6,#0
blt 5f
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r7,r7,#1
sub r6,r6,#1
b 4b @ and loop
5:
mov r9,#0
6: @ copy loop word to buffer
ldrb r0,[r8,r9]
cmp r0,#'$'
beq 7f
cmp r0,#0 @ line end
beq 8f
strb r0,[fp,r7]
add r7,r7,#1
add r9,r9,#1
b 6b
7:
add r8,r8,r9
add r8,r8,#1 @ new word begin
mov r6,#0 @ raz word length
add r4,r4,#1 @ increment line indice
b 2b
8:
mov r0,#'\n'
strb r0,[fp,r7] @ return line
add r7,r7,#1
mov r0,#0
strb r0,[fp,r7] @ final zéro
mov r0,fp
bl affichageMess @ display output buffer
add r2,r2,#1
cmp r2,#NBLINES
blt 1b
100:
add sp,sp,#BUFFERSIZE
pop {r4-r9,fp,pc}
/******************************************************************/
/* align center */
/******************************************************************/
/* r0 contains the address of pointer array*/
/* r1 contains column size */
alignCenter:
push {r4-r12,lr} @ save registers
sub sp,sp,#BUFFERSIZE @ reserve place for output buffer
mov fp,sp
mov r5,r0 @ array address
mov r2,#0 @ indice array
1:
ldr r3,[r5,r2,lsl #2] @ load line pointer
mov r4,#0 @ line character indice
mov r7,#0 @ output buffer character indice
mov r6,#0 @ word length
mov r8,r3 @ word begin address
2: @ compute word length
ldrb r0,[r3,r4] @ load a character line
cmp r0,#0 @ line end ?
beq 3f
cmp r0,#'$' @ separator ?
beq 3f
add r4,r4,#1 @ increment line indice
add r6,r6,#1 @ increment word length
b 2b
3:
cmp r6,#0
beq 5f
sub r6,r1,r6 @ total spaces number to add
mov r12,r6
lsr r6,r6,#1 @ divise by 2 = left spaces number
4:
cmp r6,#0
blt 5f
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r7,r7,#1 @ increment output indice
sub r6,r6,#1 @ decrement number space
b 4b @ and loop
5:
mov r9,#0
6: @ copy loop word to buffer
ldrb r0,[r8,r9]
cmp r0,#'$' @ séparator ?
beq 7f
cmp r0,#0 @ line end ?
beq 10f
strb r0,[fp,r7]
add r7,r7,#1
add r9,r9,#1
b 6b
7:
lsr r6,r12,#1 @ divise total spaces by 2
sub r6,r12,r6 @ and compute number spaces to right side
8: @ loop to add right spaces
cmp r6,#0
ble 9f
mov r0,#' '
strb r0,[fp,r7] @ add space to buffer
add r7,r7,#1
sub r6,r6,#1
b 8b @ and loop
9:
add r8,r8,r9
add r8,r8,#1 @ new address word begin
mov r6,#0 @ raz word length
add r4,r4,#1 @ increment line indice
b 2b @ and loop new word
10:
mov r0,#'\n'
strb r0,[fp,r7] @ return line
add r7,r7,#1
mov r0,#0
strb r0,[fp,r7] @ final zéro
mov r0,fp
bl affichageMess @ display output buffer
add r2,r2,#1 @ increment line indice
cmp r2,#NBLINES @ maxi ?
blt 1b @ loop
100:
add sp,sp,#BUFFERSIZE
pop {r4-r12,pc}
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
LEFT :
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
RIGHT :
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
CENTER :
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">text: {
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
}
output: map split.lines text => [split.by:"$" &]
loop output 'line [
loop line 'word -> prints pad word 12
print ""
]</syntaxhighlight>
{{out}}
<pre> Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Alignment := "L" ; Options: L, R, C
Text =
( LTrim
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
)
Loop, Parse, Text ; calculate column's width
If A_LoopField in $,`n
If (N > W)
W := N, N := 0
Else
N := 0
Else
++N
Width := ++W
Loop, Parse, Text, `n ; process each line
{
Words := StrSplit(A_LoopField, "$")
For i, Word in Words ; process each word
Line .= Align(Word, Alignment, Width)
Result .= RTrim(Line) . "`n"
Line := ""
}
Clipboard := Result ; present results
MsgBox, The results are in the Clipboard
Align(Pal, How, Width) { ; function for alignment
Length := StrLen(Pal)
If (How = "L")
Return Pal . Spc(Width - Length)
Else If (How = "R")
Return Spc(Width - Length) . Pal
Else If (How = "C")
Return Spc((Width - Length)//2) . Pal . Spc(Width - Length - (Width - Length)//2)
}
Spc(Number) { ; function to concatenate space characters
Loop, %Number%
Ret .= A_Space
Return Ret
}
</syntaxhighlight>
=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">
; == If the given text is in an file, it will read with:
#include <File.au3>
Line 820 ⟶ 2,171:
EndSwitch
EndFunc ;==>_GetAligned
</syntaxhighlight>
Example output in Alignment: left - center - right - left - center - right - left - center - right - left - center - right
<pre>
Line 830 ⟶ 2,181:
justified, right justified, or center justified within its column.
</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT
BEGIN {
Line 873 ⟶ 2,225:
}
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
<p>Output:</p>
<pre>
Line 909 ⟶ 2,261:
</pre>
=={{header|
<syntaxhighlight lang="freebasic">
DECLARE in$[] = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", \
"are$delineated$by$a$single$'dollar'$character,$write$a$program", \
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", \
"column$are$separated$by$at$least$one$space.", \
"Further,$allow$for$each$word$in$a$column$to$be$either$left$", \
"justified,$right$justified,$or$center$justified$within$its$column." }
OPTION DELIM "$"
CONST items = 6
SUB Print_In_Columns(style)
' Find widest column
FOR y = 0 TO items-1
FOR x = 1 TO AMOUNT(in$[y])
IF LEN(TOKEN$(in$[y], x)) > max THEN max = LEN(TOKEN$(in$[y], x))
' Print aligned
FOR y = 0 TO items-1
FOR x = 1 TO AMOUNT(in$[y])
PRINT ALIGN$(TOKEN$(in$[y], x), max+1, style);
NEXT
PRINT
NEXT
PRINT
END SUB
Print_In_Columns(0)
Print_In_Columns(1)
Print_In_Columns(2)
</syntaxhighlight>
{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
Line 1,026 ⟶ 2,327:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
DATA "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
DATA "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Line 1,081 ⟶ 2,382:
WHEN "right": = STRING$(field%-LEN(word$), " ") + word$
ENDCASE
= word$</
==={{header|Commodore BASIC}}===
<
20 rem print words in columns
30 rem commodore basic 2.0
Line 1,149 ⟶ 2,450:
640 data "column$are$separated$by$at$least$one$space."
650 data "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
660 data "justified,$right$justified,$or$center$justified$within$its$column"</
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
mode con cols=103
echo Given$a$text$file$of$many$lines,$where$fields$within$a$line$ >file.txt
echo are$delineated$by$a$single$'dollar'$character,$write$a$program! >>file.txt
echo that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$>>file.txt
echo column$are$separated$by$at$least$one$space.>>file.txt
echo Further,$allow$for$each$word$in$a$column$to$be$either$left$>>file.txt
echo justified,$right$justified,$or$center$justified$within$its$column.>>file.txt
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:maxlen %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
echo.
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:align 1 %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
echo.
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:align 2 %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
echo.
for /f "tokens=1-13 delims=$" %%a in ('type file.txt') do (
call:align 3 %%a %%b %%c %%d %%e %%f %%g %%h %%i %%j %%k %%l %%m )
exit /B
:maxlen &::sets variables len1 to len13
set "cnt=1"
:loop1
if "%1"=="" exit /b
call:strlen %1 length
if !len%cnt%! lss !length! set len%cnt%=!length!
set /a cnt+=1
shift
goto loop1
:align
setlocal
set cnt=1
set print=
:loop2
if "%2"=="" echo(%print%&endlocal & exit /b
set /a width=len%cnt%,cnt+=1
set arr=%2
if %1 equ 1 call:left %width% arr
if %1 equ 2 call:right %width% arr
if %1 equ 3 call:center %width% arr
set "print=%print%%arr% "
shift /2
goto loop2
:left %num% &string
setlocal
set "arr=!%2! "
set arr=!arr:~0,%1!
endlocal & set %2=%arr%
exit /b
:right %num% &string
setlocal
set "arr= !%2!"
set arr=!arr:~-%1!
endlocal & set %2=%arr%
exit /b
:center %num% &string
setlocal
set /a width=%1-1
set arr=!%2!
:loop3
if "!arr:~%width%,1!"=="" set "arr=%arr% "
if "!arr:~%width%,1!"=="" set "arr= %arr%"
if "!arr:~%width%,1!"=="" goto loop3
endlocal & set %2=%arr%
exit /b
:strlen StrVar &RtnVar
setlocal EnableDelayedExpansion
set "s=#%~1"
set "len=0"
for %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%N,1!" neq "" set /a "len+=%%N" & set "s=!s:~%%N!"
)
endlocal & set %~2=%len%
exit /b</syntaxhighlight>
{{out}}
<pre>Given a text file of many lines where fields within a line
are delineated by a single 'dollar' character write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further allow for each word in a column to be either left
justified right justified or center justified within its column.
Given a text file of many lines where fields within a line
are delineated by a single 'dollar' character write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further allow for each word in a column to be either left
justified right justified or center justified within its column.
Given a text file of many lines where fields within a line
are delineated by a single 'dollar' character write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further allow for each word in a column to be either left
justified right justified or center justified within its column.</pre>
=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program 'Align columns'
const
text = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'''
var
words : array^2 of str
widths : array of num
calc div_line
var s = '+'
loop across:widths val:w
s = s & str_repeat('-',w) & '+'
log s
calc show_table(
justify
)
loop across:words index:i
var s = '|'
loop across:widths index:j val:w
var
word = words[i,j]
if word == U
word = ''
case justify
| RIGHT
s = s & pad_left(word,w)
| LEFT
s = s & pad_right(word,w)
| CENTER
w = w - str_len(word)
s = s & str_repeat(' ',idiv(w,2)) & word & str_repeat(' ',idiv(w,2)+mod(w,2))
s = s & '|'
log s
div_line
calc main_init
var w
split_lines_words (text, words, delim:'$')
loop across:words index:i
loop across:words[i] index:j
w = str_len(words[i,j])
widths[j] = max(w,widths[j])
loop across:[LEFT CENTER RIGHT] val:v
log "\n{v} justified\n"
div_line
show_table(v)</syntaxhighlight>
{{out}}
<pre>
LEFT justified
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|Given |a |text |file |of |many |lines, |where |fields |within |a |line|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|are |delineated|by |a |single|'dollar' |character,|write |a |program| | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|that |aligns |each |column|of |fields |by |ensuring|that |words |in |each|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|column |are |separated |by |at |least |one |space. | | | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|Further, |allow |for |each |word |in |a |column |to |be |either|left|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|justified,|right |justified,|or |center|justified|within |its |column.| | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
CENTER justified
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Given | a | text | file | of | many | lines, | where |fields |within | a |line|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| are |delineated| by | a |single|'dollar' |character,| write | a |program| | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| that | aligns | each |column| of | fields | by |ensuring| that | words | in |each|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| column | are |separated | by | at | least | one | space. | | | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Further, | allow | for | each | word | in | a | column | to | be |either|left|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|justified,| right |justified,| or |center|justified| within | its |column.| | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
RIGHT justified
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Given| a| text| file| of| many| lines,| where| fields| within| a|line|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| are|delineated| by| a|single| 'dollar'|character,| write| a|program| | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| that| aligns| each|column| of| fields| by|ensuring| that| words| in|each|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| column| are| separated| by| at| least| one| space.| | | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Further,| allow| for| each| word| in| a| column| to| be|either|left|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|justified,| right|justified,| or|center|justified| within| its|column.| | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
</pre>
=={{header|BQN}}==
A function which returns a rectangular 2D array which represents the lines.
<syntaxhighlight lang="bqn">Split ← (⊢-˜+`׬)∘=⊔⊢
PadRow ← {
w‿t𝕊𝕩: # t → type.
# 0 → left
# 1 → right
# 2 → center
pstyle←t⊑⟨{0‿𝕩},{𝕩‿0},{⟨⌊𝕩÷2,⌈𝕩÷2⟩}⟩
𝕩{(⊣∾𝕨∾⊢)´(Pstyle 𝕩)/¨<w}¨(⌈´-⊢)≠¨𝕩
}
Align ← {{𝕨∾' '∾𝕩}´˘⍉" "‿𝕨⊸PadRow˘⍉>⟨""⟩‿0 PadRow '$' Split¨(@+10) Split 𝕩}
1 Align text</syntaxhighlight>
<syntaxhighlight lang="bqn">┌─
╵" Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. "
┘</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=dGV4dOKGkCJHaXZlbiRhJHRleHQkZmlsZSRvZiRtYW55JGxpbmVzLCR3aGVyZSRmaWVsZHMkd2l0aGluJGEkbGluZSQKYXJlJGRlbGluZWF0ZWQkYnkkYSRzaW5nbGUkJ2RvbGxhcickY2hhcmFjdGVyLCR3cml0ZSRhJHByb2dyYW0KdGhhdCRhbGlnbnMkZWFjaCRjb2x1bW4kb2YkZmllbGRzJGJ5JGVuc3VyaW5nJHRoYXQkd29yZHMkaW4kZWFjaCQKY29sdW1uJGFyZSRzZXBhcmF0ZWQkYnkkYXQkbGVhc3Qkb25lJHNwYWNlLgpGdXJ0aGVyLCRhbGxvdyRmb3IkZWFjaCR3b3JkJGluJGEkY29sdW1uJHRvJGJlJGVpdGhlciRsZWZ0JApqdXN0aWZpZWQsJHJpZ2h0JGp1c3RpZmllZCwkb3IkY2VudGVyJGp1c3RpZmllZCR3aXRoaW4kaXRzJGNvbHVtbi4iCgpTcGxpdCDihpAgKOKKoi3LnCtgw5fCrCniiJg94oqU4oqiClBhZFJvdyDihpAgewogIHfigL908J2VivCdlak6ICMgdCDihpIgdHlwZS4KICAgICAgICAjIDAg4oaSIGxlZnQKICAgICAgICAjIDEg4oaSIHJpZ2h0CiAgICAgICAgIyAyIOKGkiBjZW50ZXIKIHBzdHlsZeKGkHTiipHin6h7MOKAv/Cdlal9LHvwnZWp4oC/MH0se+KfqOKMivCdlanDtzIs4oyI8J2VqcO3MuKfqX3in6kKIPCdlal7KOKKo+KIvvCdlajiiL7iiqIpwrQoUHN0eWxlIPCdlakpL8KoPHd9wqgo4oyIwrQt4oqiKeKJoMKo8J2VqQp9CkFsaWduIOKGkCB7e/CdlajiiL4nICfiiL7wnZWpfcK0y5jijYkiICLigL/wnZWo4oq4UGFkUm93y5jijYk+4p+oIiLin6nigL8wIFBhZFJvdyAnJCcgU3BsaXTCqChAKzEwKSBTcGxpdCDwnZWpfQoKMSBBbGlnbiB0ZXh0CgoK Try It!]
=={{header|C}}==
See [[Column Aligner/C]]
=={{header|C sharp|C#}}==
===Old version===
Uses a delegate, which were added to the language in C# 2, to define left-, right-, or center-justified.
{{works with|C sharp|C#|2+}}
<
class ColumnAlignerProgram
{
Line 1,232 ⟶ 2,768:
}
}
}</
===Newer version===
Uses features of newer versions, like LINQ, lambdas and switch expressions.
{{works with|C sharp|C#|8+}}
<syntaxhighlight lang="csharp">using System;
using System.Linq;
enum Justification { Left, Center, Right }
public class Program
{
static void Main()
{
string text =
@"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.";
AlignColumns(text, Justification.Left);
Console.WriteLine();
AlignColumns(text, Justification.Center);
Console.WriteLine();
AlignColumns(text, Justification.Right);
}
public static void AlignColumns(string text, Justification justification) =>
AlignColumns(text.Split(Environment.NewLine), justification);
public static void AlignColumns(string[] lines, Justification justification) =>
AlignColumns(lines.Select(line => line.Split('$')).ToArray(), justification);
public static void AlignColumns(string[][] table, Justification justification)
{
Console.WriteLine(justification + ":");
int columns = table.Max(line => line.Length);
var columnWidths =
Enumerable.Range(0, columns)
.Select(i => table.Max(line => i < line.Length ? line[i].Length : 0)
).ToArray();
foreach (var line in table) {
Console.WriteLine(string.Join(" ",
Enumerable.Range(0, line.Length)
.Select(i => justification switch {
Justification.Left => line[i].PadRight(columnWidths[i]),
Justification.Right => line[i].PadLeft(columnWidths[i]),
_ => line[i].PadLeft(columnWidths[i] / 2).PadRight(columnWidths[i])
})
));
}
}
}</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Left:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Center:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Right:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|C++}}==
Line 1,249 ⟶ 2,856:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(ns rosettacode.align-columns
(:require [clojure.contrib.string :as str]))
Line 1,291 ⟶ 2,898:
(print-table (aligned-table table :center))
</syntaxhighlight>
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
identification division.
program-id. AlignColumns.
data division.
working-storage section.
*>-> Constants
78 MAX-LINES value 6.
78 MAX-LINE-SIZE value 66.
78 MAX-COLUMNS value 12.
78 MAX-COLUMN-SIZE value 16.
*>-> Indexes
01 w-idx pic is 9(2).
01 w-idy pic is 9(2).
01 w-pos pic is 9(3).
*>-> Data structures
01 w-lines.
05 w-line pic is x(MAX-LINE-SIZE) occurs MAX-LINES.
01 w-column-sizes.
05 w-column-size pic is 99 occurs MAX-COLUMNS value zeros.
01 w-matrix.
05 filler occurs MAX-LINES.
10 filler occurs MAX-COLUMNS.
15 w-content pic is x(MAX-COLUMN-SIZE).
*>-> Output
01 w-line-out pic is x(120).
*>-> Data alignment
01 w-alignment pic is x(1).
88 alignment-left value is "L".
88 alignment-center value is "C".
88 alignment-right value is "R".
procedure division.
main.
move "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" to w-line(1)
move "are$delineated$by$a$single$'dollar'$character,$write$a$program" to w-line(2)
move "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" to w-line(3)
move "column$are$separated$by$at$least$one$space." to w-line(4)
move "Further,$allow$for$each$word$in$a$column$to$be$either$left$" to w-line(5)
move "justified,$right$justified,$or$center$justified$within$its$column." to w-line(6)
perform calculate-size-columns
set alignment-left to true
perform show-content
set alignment-center to true
perform show-content
set alignment-right to true
perform show-content
goback
.
calculate-size-columns.
perform
varying w-idx from 1 by 1
until w-idx > MAX-LINES
unstring w-line(w-idx) delimited by "$" into w-content(w-idx, 1), w-content(w-idx, 2),
w-content(w-idx, 3), w-content(w-idx, 4), w-content(w-idx, 5), w-content(w-idx, 6),
w-content(w-idx, 7), w-content(w-idx, 8), w-content(w-idx, 9), w-content(w-idx, 10),
w-content(w-idx, 11), w-content(w-idx, 12),
perform
varying w-idy from 1 by 1
until w-idy > MAX-COLUMNS
if function stored-char-length(w-content(w-idx, w-idy)) > w-column-size(w-idy)
move function stored-char-length(w-content(w-idx, w-idy)) to w-column-size(w-idy)
end-if
end-perform
end-perform
.
show-content.
move all "-" to w-line-out
display w-line-out
perform
varying w-idx from 1 by 1
until w-idx > MAX-LINES
move spaces to w-line-out
move 1 to w-pos
perform
varying w-idy from 1 by 1
until w-idy > MAX-COLUMNS
call "C$JUSTIFY" using w-content(w-idx, w-idy)(1:w-column-size(w-idy)), w-alignment
move w-content(w-idx, w-idy) to w-line-out(w-pos:w-column-size(w-idy))
compute w-pos = w-pos + w-column-size(w-idy) + 1
end-perform
display w-line-out
end-perform
.
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
------------------------------------------------------------------------------------------------------------------------
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
------------------------------------------------------------------------------------------------------------------------
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
------------------------------------------------------------------------------------------------------------------------
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
=={{header|CoffeeScript}}==
<
pad = (n) ->
s = ''
Line 1,343 ⟶ 3,061:
console.log "\n----- #{alignment}"
align input, alignment
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="text">
> coffee align_columns.coffee
Line 1,371 ⟶ 3,089:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(position-if (lambda (x) (declare (ignore x)) t) seq))
Line 1,421 ⟶ 3,139:
(format s "~~~d~a<~~a~~>" (1+ w) fmtmod))
(princ "~}~%~}" s))
fields))</
=={{header|D}}==
<
import std.stdio, std.string, std.algorithm, std.range, std.typetuple;
Line 1,445 ⟶ 3,163:
writefln("%-(%s %)", line.length.iota
.map!(i => just(line[i], maxWidths[i], ' ')));
}</
{{out}}
<pre>Given a txt file of many lines, where fields within a line
Line 1,468 ⟶ 3,186:
=={{header|Delphi}}==
{{libheader|Delphi StdCtrls, Classes, SysUtils, StrUtils, Contnrs}}
<syntaxhighlight lang="delphi">
USES
StdCtrls, Classes, SysUtils, StrUtils, Contnrs;
Line 1,525 ⟶ 3,243:
END;
end;
</syntaxhighlight>
=={{header|E}}==
<
def left(width, word) {
Line 1,557 ⟶ 3,275:
} + "\n"
}
}</
<
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 1,588 ⟶ 3,306:
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</
=={{header|EasyLang}}==
{{trans|AWK}}
<syntaxhighlight>
global width inp$[] .
proc read . .
repeat
inp$ = input
until inp$ = ""
inp$[] &= inp$
ar$[] = strsplit inp$ "$"
for s$ in ar$[]
width = higher width len s$
.
.
.
read
#
proc out mode . .
for inp$ in inp$[]
ar$[] = strsplit inp$ "$"
for s$ in ar$[]
spc = width - len s$ + 1
if mode = 1
write s$
for i to spc
write " "
.
elif mode = 2
for i to spc
write " "
.
write s$
elif mode = 3
for i to spc div 2
write " "
.
write s$
for i to spc - spc div 2
write " "
.
.
.
print ""
.
.
out 1
print ""
out 2
print ""
out 3
#
input_data
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
</syntaxhighlight>
=={{header|Elixir}}==
Line 1,595 ⟶ 3,375:
The String module of Elixir doesn't have the function of the center position adjusting.
It calls and processes the function of 'Erlang'.
<
def columns(text, alignment) do
fieldsbyrow = String.split(text, "\n", trim: true)
Line 1,629 ⟶ 3,409:
IO.puts "\n# #{alignment} Column-aligned output:"
Align.columns(text, alignment)
end)</
{{out}}
Line 1,659 ⟶ 3,439:
=={{header|Erlang}}==
<
-module (align_columns).
Line 1,697 ⟶ 3,477:
Zipped = lists:zip (All_words, Words_length),
[ apply(string, Alignment, [Word, Length + 1, $\s])
|| {Word, Length} <- Zipped]. </
{{out}}
Line 1,730 ⟶ 3,510:
=={{header|Euphoria}}==
<
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
Line 1,790 ⟶ 3,570:
end for
puts(1,'\n')
end for</
{{out}}
Line 1,817 ⟶ 3,597:
=={{header|F_Sharp|F#}}==
<
open System.IO
Line 1,849 ⟶ 3,629:
format table align
printfn "%s" (new String('-', (Array.sum width) + width.Length - 1))
0</
Output, when called with a file containing the sample input
<pre>Given a text file of many lines, where fields within a line
Line 1,874 ⟶ 3,654:
=={{header|Factor}}==
<
splitting strings ;
IN: rosetta.column-aligner
Line 1,913 ⟶ 3,693:
: print-aligned ( text alignment -- )
[ split-and-pad flip ] dip align-columns flip
[ [ write " " write ] each nl ] each ;</
example-text { +left+ +middle+ +right+ } [ print-aligned ] with each
Line 1,919 ⟶ 3,699:
=={{header|FBSL}}==
Using a multiline string:
<
DIM s = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 1,953 ⟶ 3,733:
NEXT
PAUSE</
{{out}}
Given a text file of many lines, where fields within a line
Line 1,966 ⟶ 3,746:
=={{header|Forth}}==
{{works with|GNU Forth}}
<
: split ( addr len char -- addr len1 addr len-len1 )
Line 2,035 ⟶ 3,815:
\ cleanup
nip free throw
column-widths free throw</
=={{header|Fortran}}==
Line 2,053 ⟶ 3,833:
Given a FORMAT text that produces output in aligned columns makes it easy enough to meet the other requirements. To cause texts to be aligned left, append sufficient spaces to each output text, and for centred text, half that number. This relies on the special intrinsic function REPEAT(text,n) returning a varying number of characters - CHARACTER functions have to return a ''fixed'' number of characters, until the standardisation of varying-length strings in F2003 ''et seq''. Earlier Fortrans lack the REPEAT function, but its effect can be gained via something like CHARACTER*66 SPACE, where SPACE is set to spaces, and SPACE(1:N) is used where REPEAT(" ",N) is desired. And if messing with variable FORMAT is unwanted, the REPEAT scheme can be used for the right-justified output also.
<syntaxhighlight lang="fortran">
SUBROUTINE RAKE(IN,M,X,WAY) !Casts forth text in fixed-width columns.
Collates column widths so that each column is wide enough for its widest member.
Line 2,148 ⟶ 3,928:
CALL RAKE(IN,M,"$",+1) !Align right.
END !That's all.
</syntaxhighlight>
Every line of output starts with a space, and if it were to be sent to a lineprinter, this would be used as the carriage control character (meaning, advance one line then print the rest) - the first column does not need to be set off by one space from the previous column, but rather than devise special treatment it is spaced off anyway. The free-format output statements also start with a space. Output:
<pre>
Line 2,182 ⟶ 3,962:
=={{header|FreeBASIC}}==
<
Sub Split(s As String, sep As String, result() As String)
Line 2,279 ⟶ 4,059:
Next i
Close #1 : Close #2 : Close #3</
{{out}}
Line 2,317 ⟶ 4,097:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|FutureBasic}}==
Note: FB's NSLog, used for demonstrations, does not have a center alignment provision. However FB allows advanced alignment and text formatting in normal application development. Simple right and left alignment are shown here.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
local fn AlignColumn
NSUInteger i
CFStringRef testStr = @"Given$a$text$file$of$many$lines,$where$fields$within$a$line$are$delineated$by¬
$a$single$'dollar'$character,$write$a$program$that$aligns$each$column$of$fields$by$ensuring$that$words¬
$in$each$column$are$separated$by$at$least$one$space.$Further,$allow$for$each$word$in$a$column$to$be¬
$either$left$justified$right$justified,$or$center$justified$within$its$column."
CFArrayRef temp = fn StringComponentsSeparatedByString( testStr, @"$" )
CFMutableArrayRef arr = fn MutableArrayWithArray( temp )
NSUInteger count = fn ArrayCount( arr )
ptr a(50)
NSLog( @"\nLeft aligned:\n" )
NSUInteger lineCheck = 1
for i = 0 to count -1
a( lineCheck ) = (ptr)fn StringUTF8String( arr[i] )
if ( lineCheck == 9 )
NSLog( @"%-12s %-11s %-12s %-11s %-12s %-12s %-12s %-12s %-12s", a(1),a(2),a(3),a(4),a(5),a(6),a(7),a(8),a(9) )
lineCheck = 1
else
lineCheck++
end if
next
NSLog( @"\n\nRight aligned:\n" )
lineCheck = 1
for i = 0 to count -1
a( lineCheck ) = (ptr)fn StringUTF8String( arr[i] )
if ( lineCheck == 9 )
NSLog( @"%12s %11s %12s %11s %12s %12s %12s %12s %12s", a(1),a(2),a(3),a(4),a(5),a(6),a(7),a(8),a(9) )
lineCheck = 1
else
lineCheck++
end if
next
end fn
fn AlignColumn
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Left aligned:
Given a text file of many lines, where fields
within a line are delineated by a single 'dollar'
character, write a program that aligns each column of
fields by ensuring that words in each column are
separated by at least one space. Further, allow for
each word in a column to be either left
justified right justified, or center justified within its column.
Right aligned:
Given a text file of many lines, where fields
within a line are delineated by a single 'dollar'
character, write a program that aligns each column of
fields by ensuring that words in each column are
separated by at least one space. Further, allow for
each word in a column to be either left
justified right justified, or center justified within its column.
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=023b4c5144d45e047abe02ebf5c4525a Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main() 'Written in Gambas 3.9.2 as a Command line Application - 15/03/2017
Dim siCount, siCounter, siLength As Short 'Counters
Dim siLongest As Short = -1 'To store the longest 'Word'
Dim sLine, sRows As New String[] 'Arrays
Dim sTemp, sAlign As String 'Temp strings
Dim sInput As String = "Given$a$text$file$of$many$lines, $where$fields$within$a$line$" & "\n"
"are$delineated$by$a$single$ 'dollar'$character,$write$a$program" & "\n"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & "\n"
"column$are$separated$by$at$least$one$space." & "\n"
"Further, $allow$for$each$word$in$a$column$to$be$either$left$" & "\n"
"justified, $right$justified, $or$center$justified$within$its$column." 'Main string (with End Of Line characters added)
For Each sTemp In Split(sInput, "\n") 'For each Line (split by End of Line character)..
sLine.add(sTemp) 'Add the Line to sLine array
Next
For siCount = 0 To sLine.Max 'For each of Lines in the array..
For Each sTemp In Split(sLine[siCount], "$") 'For each 'Word' in the Line (Split by the '$')
siLength = Len(sTemp) 'Store the length of the current 'Word'
If siLength > siLongest Then siLongest = siLength 'Make sure siLength has the length of the longest 'Word'
sRows.add(Trim(sTemp)) 'Create an array of the 'Words'
Next
sRows.add("\n") 'Add a End Of Line character to the sRows array
Next
For siCounter = 0 To 2 'For each alignment (Left, Right and Centre)
For Each sTemp In sRows 'For each 'Word' in the sRows array..
If sTemp = "\n" Then 'If it's a End Of Line character then..
Print 'Print
Continue 'Jump to the next iteration of the For Next Loop
Endif
If siCounter = 0 Then Print sTemp & Space(siLongest - Len(sTemp)); 'Print control for Left align
If siCounter = 1 Then Print Space(siLongest - Len(sTemp)) & sTemp; 'Print control for Right align
If siCounter = 2 Then 'Print control for Centre align
siCount = (siLongest - Len(sTemp)) / 2 'Difference between the length of the longest 'Word' and the current 'Word' / 2
sAlign = Space(siCount) & sTemp & Space(siCount) 'Put the string together for printing
If Len(sAlign) < siLongest Then sAlign &= " " 'Check it's the correct length if not add a space on the end
Print sAlign; 'Print the 'Word'
Endif
Next
Print 'Print an empty line between each alignment list
Next
End</syntaxhighlight>
{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Go}}==
<
import (
Line 2,380 ⟶ 4,306:
f.print(middle)
f.print(right)
}</
<pre>
Given a text file of many lines, where fields within a line
Line 2,406 ⟶ 4,332:
=={{header|Groovy}}==
Solution:
<
def lines = rawText.tokenize('\n')
def words = lines.collect { it.tokenize(/\$/) }
Line 2,419 ⟶ 4,345:
words.each { padAll(justify[align], columnWidths, it).each { print it }; println() }
}</
Test Program:
<
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 2,433 ⟶ 4,359:
alignColumns(align, rawTextInput)
println()
}</
{{out}}
Line 2,459 ⟶ 4,385:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">
PROCEDURE Main()
LOCAL a := { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",;
"are$delineated$by$a$single$'dollar'$character,$write$a$program",;
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",;
"column$are$separated$by$at$least$one$space.",;
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",;
"justified,$right$justified,$or$center$justified$within$its$column." }
LOCAL e, nMax
// remove trailing dollars
AEval( a, {|e,n| Iif( Right(e,1)=="$", a[n] := hb_StrShrink( e, 1 ), NIL ) } )
// find max word length
nMax := 0
AEval( a, {|e| AEval( hb_Atokens( e, "$"), {|i| nMax := Max( nMax, Len(i) )} ) } )
nMax++
// start printing, padding words as needed
?
? "----Left aligned columns----"
FOR EACH e IN a
?
AEval( hb_Atokens( e, "$"), {|i| QQout( PadR(i, nMax) )} )
NEXT
?
? "----Center aligned columns----"
FOR EACH e IN a
?
AEval( hb_Atokens( e, "$"), {|i| QQout( PadC(i, nMax) )} )
NEXT
?
? "----Right aligned columns----"
FOR EACH e IN a
?
AEval( hb_Atokens( e, "$"), {|i| QQout( PadL(i, nMax) )} )
NEXT
RETURN
</syntaxhighlight>
Output:
<syntaxhighlight lang="text">----Left aligned columns----
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
----Center aligned columns----
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
----Right aligned columns----
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</syntaxhighlight>
=={{header|Haskell}}==
<
import Control.
dat =
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n" ++
"justified,$right$justified,$or$center$justified$within$its$column.\n"
brkdwn =
takeWhile (not . null) . unfoldr (Just . second (drop 1) . span ('$' /=))
format j ls = map (unwords . zipWith align colw) rows
where
rows = map brkdwn $ lines ls
colw = map (maximum . map length) . transpose $ rows
align cw w =
case j of
'c' ->
'r' ->
'l' -> w ++
{{out}}
<pre>
Line 2,499 ⟶ 4,495:
Or, using '''Text''' and its functions as an alternative to '''[Char]''' strings:
<syntaxhighlight lang
import Data.Text as T
(Text, pack, unpack, splitOn, unlines, unwords, length,
justifyLeft, justifyRight, center
import Data.List (transpose, zip, maximumBy)
import Data.Ord (comparing)
rows :: [[Text]]
rows =
Line 2,515 ⟶ 4,512:
, "justified,$right$justified,$or$center$justified$within$its$column."
]
cols :: [[Text]]
cols =
transpose $
((++) <*>
(flip P.replicate (pack []) .
(-) (maximum (P.length <$> rows)) . P.length)) <$>
rows
main :: IO ()
main =
Line 2,532 ⟶ 4,529:
(zip cols ((T.length . maximumBy (comparing T.length)) <$> cols))
] <*>
[justifyLeft, justifyRight, center]</
{{Out}}
<pre>Given a text file of many lines, where fields within a line
Line 2,557 ⟶ 4,554:
=={{header|HicEst}}==
A file opened with a Format option describing the column format(s) can be addressed like a standard in-memory array. In addition the DLG function ([http://www.HicEst.com/MatrixExplorer.htm MatrixExplorer]) allows this text/numeric file to be edited or visualized in many ways, but string columns are always left adjusted while numeric columns are right adjusted. Export is possible.
<syntaxhighlight lang="hicest">
CHARACTER Fnam = "\HicEst\Rosetta\Align columns.txt"
Line 2,584 ⟶ 4,581:
WRITE() out
ENDDO
END</
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
Line 2,607 ⟶ 4,604:
An argument of <tt>left</tt>, <tt>center</tt>, or <tt>right</tt> controls the
column alignment. The default is left-alignment.
<
procedure main(args)
Line 2,636 ⟶ 4,633:
write()
}
end</
Sample run:
Line 2,649 ⟶ 4,646:
=={{header|J}}==
Here, we rely on J's built-in formatting mechanism for boxed arrays, with spaces to separate the columns.
(J's [[j:Vocabulary/Foreigns#m9|9!:n]] series of conjunctions queries (even) or sets (odd) session parameters. 9!:6 queries the box display characters, and 9!:7 sets them. Here, we use spaces with 9!:7 (discarding the blank rows). Meanwhile 9!:17 determines whether box contents are left justified, center justified or right justified, and we also use that. There's some additional discussion of this approach on the [[Talk:Align_columns#J_solution|talk page]].)
'''Solution'''
<
NB.* alignCols v Format delimited text in justified columns
Line 2,667 ⟶ 4,669:
7 17 global oldbox NB. restore settings
result
)</
'''Example''':
<
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 2,693 ⟶ 4,695:
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</
=={{header|Java}}==
Line 2,700 ⟶ 4,702:
{{libheader|Apache Commons Lang}}
<
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
Line 2,843 ⟶ 4,845:
}
}
}</
=={{header|JavaScript}}==
Line 2,849 ⟶ 4,851:
===Imperative===
<syntaxhighlight lang="javascript">
var justification="center",
input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
Line 2,880 ⟶ 4,882:
for(x=0;x<input.length;x++) input[x]=input[x].join(" ");
input=input.join("\n");
document.write(input);</
===Functional===
<
var data = [
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
Line 2,931 ⟶ 4,933:
return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\n');
};</
Line 2,937 ⟶ 4,939:
Or (ES5) using transpose and zipWith:
<
'use strict';
Line 3,069 ⟶ 5,071:
Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\
justified,$right$justified,$or$center$justified$within$its$column."
);</
{{Out}}
Line 3,096 ⟶ 5,098:
=={{header|jq}}==
{{ Works with|jq|1.4}}
The key to the following implementation is the filter named "transpose", which is defined to work on a possibly jagged matrix. It is provided as a built-in in jq 1.5 and later.
<
def transpose:
if . == [] then []
Line 3,139 ⟶ 5,141:
(""; . + ($line[$i]|justify($widths[$i])) ))
| join("\n")
;</
'''Example''':
<
"Left:", format("left"), "",
"Right:", format("right")</
{{Out}}
<div style="overflow:scroll; height:200px;"><
Center:
Given a text file of many lines, where fields within a line
Line 3,169 ⟶ 5,171:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</
=={{header|Jsish}}==
From Javascript ES5 entry.
<syntaxhighlight lang="javascript">/* Align columns, in Jsish */
function alignColumns(phrases:array, just:string) {
var x, y, max, diff, left, right, cols=0;
for(x=0; x<phrases.length; x++) {
phrases[x] = phrases[x].split("$");
if (phrases[x].length>cols) cols=phrases[x].length;
}
for (x=0; x<cols; x++) {
max = 0;
for (y=0; y<phrases.length; y++) if (phrases[y][x] && max<phrases[y][x].length) max = phrases[y][x].length;
for (y=0; y<phrases.length; y++) {
if (phrases[y][x]) {
diff = (max-phrases[y][x].length)/2;
left = " ".repeat(Math.floor(diff));
right = " ".repeat(Math.ceil(diff));
if (just == "left") { right += left; left=""; }
if (just == "right") { left += right; right=""; }
phrases[y][x] = left + phrases[y][x] + right;
}
}
}
for (x=0; x<phrases.length; x++) phrases[x] = phrases[x].join(" ");
phrases = phrases.join("\n");
return phrases;
}
if (Interp.conf('unitTest')) {
var phrases = ["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column."];
for (var just of ['left', 'center', 'right']) {
var trial = phrases.slice(0);
puts(just);
puts(alignColumns(trial, just), '\n');
}
}</syntaxhighlight>
{{out}}
<pre>prompt$ jsish --U alignColumns.jsi
left
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
center
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
right
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|Julia}}==
{{trans|Python}}
<
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$
Line 3,212 ⟶ 5,285:
end
println("-"^sum(max_widths))
end</
{{out}}
<pre>
Line 3,242 ⟶ 5,315:
=={{header|Kotlin}}==
<
import java.nio.file.Files
import java.nio.file.Paths
Line 3,304 ⟶ 5,377:
else -> System.err.println("Error! Unknown alignment: " + alignment)
}
}</
=={{header|Lambdatalk}}==
The input data is a sequence of characters where words are supposed to be separated by $ and lines be ended by \$. A HTML table is used to format the output left, centered or right justified.
<syntaxhighlight lang="scheme">
{def txt
Given$a$text$file$of$many$lines,$where$fields$within$a$line\$are$delineated$by$a$single$'dollar'$character,$write$a$program\$that$aligns$each$column$of$fields$by$ensuring$that$words$in$each\$column$are$separated$by$at$least$one$space.\$Further,$allow$for$each$word$in$a$column$to$be$either$left\$justified,$right$justified,$or$center$justified$within$its$column.}
-> txt
{def columns // function's name
{def columns.r // loop function
{lambda {:just :a :b}
{if {A.empty? :a} // end of loop
then :b // return the string
else {columns.r :just // justification
{A.rest :a}. // loop on next char
{if {W.equal? {A.first :a} \} // if end of line
then < tr> :b // open a table row
else {if {W.equal? {A.first :a} $} // if space between words
then < td style="text-align::just;">:b // open a table data with justif
else {A.first :a}:b }} } }}} // else add character
{lambda {:just :txt} // main function
{table // open an HTML table
{columns.r // call the loop function
:just // justification
{A.reverse {A.split ${:txt}}} // split and reverse
. // end point
}}}}
-> columns
{columns left txt}
-> Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column..
{columns center txt} and {columns right txt} outputs can be seen in this website: http://lambdaway.free.fr/lambdawalks/?view=align_columns
</syntaxhighlight>
=={{header|Lasso}}==
<
local(text = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 3,373 ⟶ 5,491:
}
prepcols(#text)</
{{out}}
Line 3,404 ⟶ 5,522:
=={{header|Liberty BASIC}}==
<
CRLF$ =chr$( 13)
Line 3,481 ⟶ 5,599:
end function
end</
=={{header|Lua}}==
{{works with|Lua|5.1}}
<
local tWord = {} -- word table
local tColLen = {} -- maximum word length in a column
Line 3,547 ⟶ 5,665:
return output
end--alignColumn
</syntaxhighlight>
Usage Example:
<
input =
[[Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 3,564 ⟶ 5,682:
outputRight = alignColumn(input, "right")
alignColumn(input, "center", "output.txt")
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Align_Columns {
a$={Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
}
const cr$=chr$(13), lf$=chr$(10)
def c1=0, cmax=0, p1=-1, i
flush ' empty stack
for i=1 to len(a$)
select case mid$(a$,i,1)
case "$", cr$
if p1<>-1 then data (p1, c1): p1=-1: cmax=max(c1,cmax):c1=0
case lf$
data (-1,0) ' push to end of stack an array of two items (a tuple in m2000)
else case
if p1=-1 then p1=i :c1=1 else c1++
end select
next
if p1<>-1 then push (p1, c1): cmax=max(c1,cmax):c1=0
\\ so now stack of values hold all tuples.
Dim Words(), AlignType$(1 to 3)
AlignType$(1)=lambda$ (a$,wd)->field$(a$, wd)
AlignType$(2)=lambda$ (a$,wd)->{
a$=left$(a$, wd)
=left$(string$(" ", (len(a$)-wd) div 2)+a$+string$(" ",wd),wd)
}
AlignType$(3)= lambda$ (a$,wd)->format$("{0:"+str$(-wd)+"}", a$)
\\ [] return a stack object, reference and leave current stack of values a new stack
\\ Array( stack_object) empty the stack object moving items to an array
Words()=Array([])
document export$
def aline$
cmax++ ' add one space
For al=1 to 3
For i=0 to len(Words())-1
if Words(i)(0)=-1 then
' we use rtrim$() to cut trailing spaces
export$=rtrim$(aline$)+cr$+lf$ : aline$=""
else
aline$+=AlignType$(al)(mid$(a$,Words(i)(0), Words(i)(1)),cmax)
end if
next i
next
\\ export to clipboard
Clipboard export$
Rem Form 140, 60
Rem Print #-2, export$ ' render text to console without using console's columns
}
Align_Columns
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre >
=={{header|Maple}}==
Assign the sample data.
<syntaxhighlight lang="maple">
txt :=
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
Line 3,576 ⟶ 5,772:
"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n"
"justified,$right$justified,$or$center$justified$within$its$column.\n":
</syntaxhighlight>
The following procedure solves the problem. It takes the string to be operated on as input, and an optional alignment parameter, which defaults to centred alignment. The aligned text is returned, as a string, which can then be printed.
<syntaxhighlight lang="maple">
AlignColumns := proc( txt, align :: { "left", "right", "centre" } := "centre" )
uses StringTools;
Line 3,603 ⟶ 5,799:
Join( J, "\n" )
end proc:
</syntaxhighlight>
For the sample text, we get the following results.
<syntaxhighlight lang="maple">
> printf( "%s\n", AlignColumns( txt ) ):
Given a text file of many lines, where fields within a line
Line 3,634 ⟶ 5,830:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
Alternatively, this could be printed to a file (using fprintf instead of printf).
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Output with example text :
[[File:centeredtext.png]]
=={{header|MATLAB}} / {{header|Octave}}==
center-justified formatting is not implemented here
<syntaxhighlight lang="matlab">
function r = align_columns(f)
fid = fopen('align_column_data.txt', 'r');
D = {};
M = 0;
while ~feof(fid)
s = fgetl(fid);
strsplit(s,'$');
m = diff([0,find(s=='$')])-1;
M = max([M,zeros(1,length(m)-length(M))], [m,zeros(1,length(M)-length(m))]);
D{end+1}=s;
end
fclose(fid);
fprintf(1,'%%-- right-justified --%%\n')
FMT = sprintf('%%%ds ',M);
for k=1:length(D)
d = strsplit(D{k},'$');
fprintf(1,FMT,d{:});
fprintf(1,'\n');
end
fprintf(1,'%%-- left-justified --%%\n')
FMT = sprintf('%%-%ds ',M);
for k=1:length(D)
d = strsplit(D{k},'$');
fprintf(1,FMT,d{:});
fprintf(1,'\n');
end
end;
</syntaxhighlight>
{{out}}
<pre>
align_columns
%-- right-justified --%
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
%-- left-justified --%
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
Alignment = {"left": -1, "center": 0, "right": 1}
Align = {}
Align.load = function(contents)
self.lines = contents.split(char(13))
self.rows = []
self.numColumns = 0
for line in self.lines
columns = line.split("$")
if columns.len > self.numColumns then self.numColumns = columns.len
self.rows.push(columns)
end for
self.widths = []
for col in range(0, self.numColumns - 1)
maxWidth = 0
for line in self.rows
if col > line.len - 1 then continue
if line[col].len > maxWidth then maxWidth = line[col].len
end for
self.widths.push(maxWidth)
end for
end function
Align.__getField = function(word, width, alignment)
if alignment == Alignment.left then return (word + " " * width)[:width]
if alignment == Alignment.right then return (" " * width+word)[-width:]
if alignment == Alignment.center then
leftMargin = floor((width - word.len) / 2)
return (" " * leftMargin + word + " " * width)[:width]
end if
end function
Align.output = function(alignment)
for line in self.rows
for c in range(0, line.len - 1)
print self.__getField(line[c], self.widths[c], alignment) + " ", ""
end for
print
end for
end function
txt = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + char(13)
txt += "are$delineated$by$a$single$'dollar'$character,$write$a$program" + char(13)
txt += "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + char(13)
txt += "column$are$separated$by$at$least$one$space." + char(13)
txt += "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + char(13)
txt += "justified,$right$justified,$or$center$justified$within$its$column."
Align.load(txt)
print "Left alignment:"
Align.output(Alignment.left)
print
print "Right alignment:"
Align.output(Alignment.right)
print
print "Centered: "
Align.output(Alignment.center)
</syntaxhighlight>
{{out}}
<pre>
>miniscript.exe align-columns.ms
Left alignment:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Right alignment:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Centered:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|ML/I}}==
Line 3,647 ⟶ 5,987:
Note the presetting of P102 to indicate the alignment required.
<
"" Align columns - assumes macros on input stream 1, data on stream 2
MCPVAR 102
Line 3,703 ⟶ 6,043:
>
MCSET S1=1
*MCSET S10=102</
=={{header|ML/I}}==
In this example, ML/I reads its macros first, then switches input to the file containing the data to be formatted. Output is to 'standard output' or similar.
Note the presetting of P102 to indicate the alignment required.
<syntaxhighlight lang="ml/i">MCSKIP "WITH" NL
"" Align columns - assumes macros on input stream 1, data on stream 2
MCPVAR 102
"" Set P102 to alignment required:
"" 1 = centre
"" 2 = left
"" 3 = right
MCSET P102 = 1
MCSKIP MT,<>
MCINS %.
MCSKIP SL WITH *
"" Assume no more than 100 columns - P101 used for max number of fields
"" Set P variables 1-101 to 0
MCDEF ZEROPS WITHS NL AS <MCSET T1=1
%L1.MCSET PT1=0
MCSET T1=T1+1
MCGO L1 UNLESS T1 EN 102
>
ZEROPS
"" First pass - macro to accumulate max columns, and max widths
MCDEF SL N1 OPT $ N1 OR $ WITHS NL OR SPACE WITHS NL OR NL ALL
AS <MCGO L3 UNLESS T1 GR P101
MCSET P101=T1
%L3.MCSET T2=1
%L1.MCGO L0 IF T2 GR T1
MCSET T3=MCLENG(%WBT2.)
MCGO L2 UNLESS T3 GR PT2
MCSET PT2=T3
%L2.MCSET T2=T2+1
MCGO L1
>
MCSET S1=1
*MCSET S10=2
*MCSET S1=0
MCSET S4=1
""MCNOTE Max field is %P101.
""MCDEF REP NL AS <MCSET T1=1
""%L1.%PT1. MCSET T1=T1+1
""MCGO L1 UNLESS T1 GR P101
"">
""REP
MCDEF SL N1 OPT $ N1 OR $ WITHS NL OR SPACE WITHS NL OR NL ALL
AS <MCSET T2=1
%L5.MCGO L6 IF T2 GR T1
MCGO LP102
%L1.MCSET T3=%%%PT2.-MCLENG(%WBT2.)./2.
MCGO L7 IF T3 EN 0
MCSUB(< >,1,T3)%L7.%WBT2.""
MCSUB(< >,1,PT2-T3-MCLENG(%WBT2.)+1)MCGO L4
%L2.MCSUB(%WBT2.< >,1,PT2)MCGO L4
%L3.MCSUB(< >%WBT2.,1-PT2,0)""
%L4. MCSET T2=T2+1
MCGO L5
%L6.
>
MCSET S1=1
*MCSET S10=102</syntaxhighlight>
=={{header|MUMPS}}==
<
New col,half,ii,max,spaces,word
Set ii=0
Line 3,758 ⟶ 6,160:
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</
=={{header|Nim}}==
<
from sequtils import mapIt
from strfmt import format, write
let textinfile = """Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 3,770 ⟶ 6,174:
justified,$right$justified,$or$center$justified$within$its$column."""
var words = textinfile.splitLines.mapIt(
var maxs = newSeq[int](max words.mapIt(
for
for j,w in
maxs[j] = max(maxs[j], w.len+1)
for i, align in ["<",">","^"]:
echo(["Left", "Right", "Center"][i], " column-aligned output:")
for
for j,w in
stdout.write
stdout.write "\n"
stdout.write "\n"</syntaxhighlight>
{{out}}
<pre>Left column-aligned output:
Line 3,791 ⟶ 6,196:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Right column-aligned output:
Given a text file of many lines, where fields within a line
Line 3,798 ⟶ 6,204:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Center column-aligned output:
Given a text file of many lines, where fields within a line
Line 3,805 ⟶ 6,212:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. </pre>
=={{header|Nit}}==
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/align_columns.nit the official Nit’s repository]
<syntaxhighlight lang="nit"># Task: Align columns
#
# Uses `Text::justify` from the standard library.
module align_columns
fun aligner(text: String, left: Float)
do
# Each row is a sequence of fields
var rows = new Array[Array[String]]
for line in text.split('\n') do
rows.add line.split("$")
end
# Compute the final length of each column
var lengths = new Array[Int]
for fields in rows do
var i = 0
for field in fields do
var fl = field.length
if lengths.length <= i or fl > lengths[i] then
lengths[i] = fl
end
i += 1
end
end
# Process each line and align each field
for fields in rows do
var line = new Array[String]
var i = 0
for field in fields do
line.add field.justify(lengths[i], left)
i += 1
end
print line.join(" ")
end
end
var text = """
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."""
aligner(text, 0.0)
aligner(text, 1.0)
aligner(text, 0.5)</syntaxhighlight>
{{out}}
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Oberon-2}}==
works with oo2c version 2.
<
MODULE Columns;
IMPORT
Line 3,917 ⟶ 6,398:
END Columns.
</syntaxhighlight>
<pre>
Given a text file of many lines, where fields within a line
Line 3,944 ⟶ 6,425:
=={{header|OCaml}}==
<
open Str
Line 3,997 ⟶ 6,478:
let sp2 = String.make pad2 ' ' in
Printf.printf "%s%s%s " sp1 word sp2);
;;</
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">import: mapping
import: file
: <<nbl \ stream n -- stream
#[ ' ' <<c ] times ;
String method: justify( n just -- s )
| l m |
n self size - dup ->l 2 / ->m
just $RIGHT if=
just $LEFT if=
;
: align( file just -- )
| lines maxsize |
#[ wordsWith( '$' ) ] file File new map ->lines
0 #[ apply( #[ size max ] ) ] lines apply ->maxsize
;</syntaxhighlight>
{{out}}
<pre>
>"align
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
Line 4,031 ⟶ 6,518:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
text = .array~of("Given$a$text$file$of$many$lines,$where$fields$within$a$line$", -
"are$delineated$by$a$single$'dollar'$character,$write$a$program", -
Line 4,106 ⟶ 6,593:
say out~string
end
</syntaxhighlight>
<pre>
align left:
Line 4,137 ⟶ 6,624:
=={{header|OpenEdge/Progress}}==
<
i_c AS CHAR,
i_calign AS CHAR
Line 4,196 ⟶ 6,683:
alignColumns( cc, "right" ) SKIP
alignColumns( cc, "center" )
VIEW-AS ALERT-BOX.</
{{out}}
Line 4,361 ⟶ 6,848:
=={{header|Oz}}==
<
%% Lines: list of strings
%% Alignment: function like fun {Left Txt ExtraSpace} ... end
Line 4,435 ⟶ 6,922:
"justified,$right$justified,$or$center$justified$within$its$column."]
in
{ForAll {Align Lines Left} System.showInfo}</
=={{header|Pascal}}==
See [[Align_columns#Delphi | Delphi]]
modified to {{works with|Free Pascal}}
<syntaxhighlight lang="pascal">program Project1;
{$H+}//Use ansistrings
uses
Classes,
SysUtils,
StrUtils;
procedure AlignByColumn(Align: TAlignment);
const
TextToAlign =
'Given$a$text$file$of$many$lines,$where$fields$within$a$line$'#$D#$A +
'are$delineated$by$a$single$''dollar''$character,$write$a$program'#$D#$A +
'that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$'#$D#$A +
'column$are$separated$by$at$least$one$space.'#$D#$A +
'Further,$allow$for$each$word$in$a$column$to$be$either$left$'#$D#$A +
'justified,$right$justified,$or$center$justified$within$its$column.';
var
TextLine: TStringList;
TextLines: array of TStringList;
OutPutString, EmptyString, Item: string;
MaxLength, i, j: Int32;
begin
try
MaxLength := 0;
TextLine := TStringList.Create;
TextLine.Text := TextToAlign;
setlength(Textlines, TextLine.Count);
for i := 0 to TextLine.Count - 1 do
begin
Textlines[i] := TStringList.Create;
Textlines[i].Text := AnsiReplaceStr(TextLine[i], '$', #$D#$A);
end;
for i := 0 to High(TextLines) do
for j := 0 to Textlines[i].Count - 1 do
if MaxLength < Length(TextLines[i][j]) then
MaxLength := Length(TextLines[i][j]);
if MaxLength > 0 then
MaxLength := MaxLength + 2; // Add two empty spaces to it
for i := 0 to High(TextLines) do
begin
OutPutString := '';
for j := 0 to Textlines[i].Count - 1 do
begin
EmptyString := StringOfChar(' ', MaxLength);
if j <> 0 then
EmptyString[1] := '|';
Item := TextLines[i][j];
case Align of
taLeftJustify: Move(Item[1], EmptyString[2], Length(Item));
taRightJustify: Move(Item[1], EmptyString[MaxLength - Length(Item) + 1],
Length(Item));
taCenter: Move(Item[1], EmptyString[(MaxLength - Length(Item) + 1) div
2 + 1], Length(Item));
end;
OutPutString := OutPutString + EmptyString;
end;
writeln(OutPutString);
end;
finally
writeln;
FreeAndNil(TextLine);
for i := High(TextLines) downto 0 do
FreeAndNil(TextLines[i]);
end;
end;
begin
AlignByColumn(taLeftJustify);
AlignByColumn(taCenter);
AlignByColumn(taRightJustify);
end.</syntaxhighlight>
{{out}}
<pre>
Given |a |text |file |of |many |lines, |where |fields |within |a |line
are |delineated |by |a |single |'dollar' |character, |write |a |program
that |aligns |each |column |of |fields |by |ensuring |that |words |in |each
column |are |separated |by |at |least |one |space.
Further, |allow |for |each |word |in |a |column |to |be |either |left
justified, |right |justified, |or |center |justified |within |its |column.
Given | a | text | file | of | many | lines, | where | fields | within | a | line
are |delineated | by | a | single | 'dollar' |character, | write | a | program
that | aligns | each | column | of | fields | by | ensuring | that | words | in | each
column | are | separated | by | at | least | one | space.
Further, | allow | for | each | word | in | a | column | to | be | either | left
justified, | right |justified, | or | center | justified | within | its | column.
Given| a| text| file| of| many| lines,| where| fields| within| a| line
are| delineated| by| a| single| 'dollar'| character,| write| a| program
that| aligns| each| column| of| fields| by| ensuring| that| words| in| each
column| are| separated| by| at| least| one| space.
Further,| allow| for| each| word| in| a| column| to| be| either| left
justified,| right| justified,| or| center| justified| within| its| column.
</pre>
=={{header|Perl}}==
<
use strict ;
Line 4,496 ⟶ 7,081:
}
print "\n" ;
}</
a shorter solution
<
sub columns {
Line 4,521 ⟶ 7,106:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
END</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">data</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
<span style="color: #008000;">"Given$a$text$file$of$many$lines,$where$fields$within$a$line$"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"are$delineated$by$a$single$'dollar'$character,$write$a$program"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"column$are$separated$by$at$least$one$space."</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"Further,$allow$for$each$word$in$a$column$to$be$either$left$"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"justified,$right$justified,$or$center$justified$within$its$column."</span>
<span style="color: #0000FF;">}</span>
<span style="color: #008080;">function</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">out</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">first</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">delim</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">first</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">delim</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">find_from</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">first</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">delim</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">delim</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">out</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">out</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">first</span><span style="color: #0000FF;">..</span><span style="color: #000000;">delim</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">first</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">delim</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">out</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">align</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">alignment</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">alignment</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">&</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">alignment</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">else</span>
<span style="color: #000080;font-style:italic;">-- (PL if I'd written this, I'd have n-floor(n/2) on the rhs)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">&</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">AlignColumns</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">llij</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">lines</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">li</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">maxlens</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">data</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">data</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">li</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #000000;">data</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #008000;">'$'</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">li</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">)></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxlens</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">maxlens</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">)-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxlens</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">llij</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">li</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">llij</span><span style="color: #0000FF;">></span><span style="color: #000000;">maxlens</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #000000;">maxlens</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">llij</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (alignment = left/centre/right)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">align</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">maxlens</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">&</span> <span style="color: #008000;">' '</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">getc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">AlignColumns</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 4,686 ⟶ 7,201:
justified, right justified, or center justified within its column.
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
0 40 repeat var gap
( "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
"are$delineated$by$a$single$'dollar'$character,$write$a$program"
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
"column$are$separated$by$at$least$one$space."
"Further,$allow$for$each$word$in$a$column$to$be$either$left$"
"justified,$right$justified,$or$center$justified$within$its$column." )
len var lines
def alignWords /# -1/0/1 for left/center/right #/
>ps
lines for
get len for >ps
tps get gap ps> get nip 1 +
tps -1 == if -1 * align else
tps 0 == if tostr align else
tps 1 == if align else
drop drop "Wrong!" exitfor
endif endif endif
print
endfor
drop
nl
endfor
ps> drop
enddef
lines for var i
i get "$" " " subst split
len for var j
j get len dup
gap j get rot
< if swap j set else swap drop endif var gap drop
endfor
i set
endfor
-1 alignWords nl
0 alignWords nl
1 alignWords nl
drop</syntaxhighlight>
=={{header|PHP}}==
<
$j2justtype = array('L' => STR_PAD_RIGHT,
'R' => STR_PAD_LEFT,
Line 4,710 ⟶ 7,273:
$maxfields = max(array_map('count', $fieldsbyrow));
foreach (range(0, $maxfields - 1) as $col) {
$maxwidth = 0;
foreach ($fieldsbyrow as $fields)
$maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));
foreach ($fieldsbyrow as &$fields)
$fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : "", $maxwidth, ' ', $justtype);
unset($fields); // see http://bugs.php.net/29992
}
Line 4,734 ⟶ 7,297:
echo aligner($textinfile, $j);
?></
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
main =>
Text =
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.",
Lines = split(Text,"\n"),
Lines = [Line1|_],
N = len(split(strip(Line1,"$ "), "$")), % number of columns
WidthArr = {0 : _ in 1..N},
foreach (Line in Lines)
Words = split(strip(Line,"$ "), "$"),
foreach ({I,Word} in zip(1..N, Words))
WidthArr[I] := max(WidthArr[I], len(Word))
end
end,
foreach (I in 1..N)
WidthArr[I] := WidthArr[I]+1 % separate cols by at least one space
end,
foreach (Align in [left, right, center])
output_lines(Lines,N,WidthArr,Align),
nl,nl
end.
output_lines(Lines,N,WidthArr,Align) =>
foreach (Line in Lines)
Words = split(strip(Line,"$ "), "$"),
foreach ({I,Word} in zip(1..N, Words))
output_word(Word,WidthArr[I],Align)
end,
nl
end.
output_word(Word,Width,left) =>
printf("%-*s",Width,Word).
output_word(Word,Width,right) =>
printf("%*s",Width,Word).
output_word(Word,Width,_) =>
Pad = len(Word)-Width,
Pad1 is Pad div 2,
Pad2 is Pad-Pad1,
printf("%*s%s%*s",Pad1,"",Word,Pad2,"").
</syntaxhighlight>
{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|PicoLisp}}==
<
(let Lines # and of lines
(make
Line 4,757 ⟶ 7,394:
(prinl)
(for L Lines
(prinl (apply center L Sizes)) ) ) ) # and centered</
{{out}}
<pre>Given a text file of many lines, where fields within a line
Line 4,781 ⟶ 7,418:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare text character (300) varying;
declare word character (20) varying;
Line 4,819 ⟶ 7,456:
put file (output) skip;
end;
</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$file =
@'
Line 4,845 ⟶ 7,482:
}
$arr | Format-Table -HideTableHeaders -Wrap *
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 4,858 ⟶ 7,495:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
L ="Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 4,937 ⟶ 7,574:
{N2 is N1 + 1},
parse_word(T, N2, NF, TF).
</syntaxhighlight>
{{out}}
Line 4,969 ⟶ 7,606:
=={{header|PureBasic}}==
{{works with|PureBasic|4.41}}
<
If OpenConsole()
Line 5,043 ⟶ 7,680:
Data.s "Further,$allow$for$each$word$in$a$column$oo$be$either$left$"
Data.s "justified,$right$justified,$or$center$justified$within$its$column."
EndDataSection</
=={{header|Python}}==
===Procedural===
====Using f-strings====
<syntaxhighlight lang="python">from itertools import zip_longest
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."""
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} column-aligned output:\n")
for line in parts:
print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line)))
print("- " * 52)
</syntaxhighlight>
{{out}}
<pre>Left column-aligned output:
Given a txt file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Center column-aligned output:
Given a txt file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Right column-aligned output:
Given a txt file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - </pre>
====Using StringIO====
<syntaxhighlight lang="python">from StringIO import StringIO
textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 5,090 ⟶ 7,780:
infile = StringIO(textinfile)
print "\n# %s Column-aligned output:" % align
print aligner(infile, align[0])</
{{out}}
Line 5,118 ⟶ 7,808:
justified, right justified, or center justified within its column. </pre>
===
Works with Python 2 and 3.
<syntaxhighlight lang="python">'''
cat <<'EOF' > align_columns.dat
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
EOF
'''
for align in '<^>':
rows = [ line.strip().split('$') for line in open('align_columns.dat') ]
fmts = [ '{:%s%d}' % (align, max( len(row[i]) if i < len(row) else 0 for row in rows ))
for i in range(max(map(len, rows))) ]
for row in rows:
print(' '.join(fmts).format(*(row + [''] * len(fmts))))
print('')</syntaxhighlight>
====Alternative====
{{trans|D}}
<
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 5,126 ⟶ 7,839:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column."""
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
max_widths = {}
for line in parts:
for i, word in enumerate(line):
max_widths[i] = max(max_widths.get(i, 0), len(word))
for i, justify in enumerate([str.ljust, str.center, str.rjust]):
print
for line in parts:
for j, word in enumerate(line):
print
print()
print
===
====As a fold====
A fold/'''reduce''' between two transpositions.
(Selection of string justification methods via '''getattr'''):
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Variously aligned columns
from delimited text.
'''
from functools import reduce
from itertools import repeat
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test of three alignments.'''
txt = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'''
rows = [x.split('$') for x in txt.splitlines()]
table = paddedRows(max(map(len, rows)))('')(rows)
print('\n\n'.join(map(
alignedTable(table)(' '),
[-1, 0, 1] # Left, Center, Right
)))
# alignedTable :: [[String]] -> Alignment -> String -> String
def alignedTable(rows):
'''Tabulation of rows of cells, with cell alignment
specified by:
eAlign -1 = left
eAlign 0 = center
eAlign 1 = right
and separator between columns
supplied by the `sep` argument.
'''
def go(sep, eAlign):
lcr = ['ljust', 'center', 'rjust'][1 + eAlign]
# nextAlignedCol :: [[String]] -> [String] -> [[String]]
def nextAlignedCol(cols, col):
w = max(len(cell) for cell in col)
return cols + [
[getattr(s, lcr)(w, ' ') for s in col]
]
return '\n'.join([
sep.join(cells) for cells in
zip(*reduce(nextAlignedCol, zip(*rows), []))
])
return lambda sep: lambda eAlign: go(sep, eAlign)
# GENERIC -------------------------------------------------
# paddedRows :: Int -> a -> [[a]] -> [[a]]
def paddedRows(n):
'''A list of rows of even length,
in which each may be padded (but
not truncated) to length n with
appended copies of value v.'''
def go(v, xs):
def pad(x):
d = n - len(x)
return (x + list(repeat(v, d))) if 0 < d else x
return [pad(row) for row in xs]
return lambda v: lambda xs: go(v, xs) if xs else []
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. </pre>
=={{header|q}}==
<syntaxhighlight lang="q">text:(
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$";
"are$delineated$by$a$single$'dollar'$character,$write$a$program";
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$";
"column$are$separated$by$at$least$one$space.";
"Further,$allow$for$each$word$in$a$column$to$be$either$left$";
"justified,$right$justified,$or$center$justified$within$its$column." )
ta:{[aln;txt] / tabulate aligned
sl:(count'')s:"$"vs/:txt; / strings and their lengths
cw:{rl#\:max x@/:\:til max rl:count each x}sl; / cell widths
ps:$[aln=`R;-1-cw;1+cw]$''s; / padded strings
ps:$[aln=`C;(neg(cw-sl)div 2)rotate''ps;ps]; / center
1,[;"\n\n"]"\n"sv raze each ps; } / print</syntaxhighlight>
{{out}}
<pre>q)ta[`L]text
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
q)ta[`R]text
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
q)ta[`C]text
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
[https://code.kx.com/q/ref/ Q Reference Card]
=={{header|R}}==
<
lines <- readLines(tc <- textConnection("Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 5,189 ⟶ 8,024:
print0(leftjust)
print0(rightjust)
print0(centrejust)</
Right justified output shown.
<div style="width:full;overflow:scroll"><pre>
Line 5,201 ⟶ 8,036:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 5,236 ⟶ 8,071:
(display-aligned #:justify 'right text)
(display-aligned #:justify 'center text)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
Call with parameter left (default), center or right.
<syntaxhighlight lang="raku" line>my @lines =
q|Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
|.lines;
my @widths;
for @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } }
for @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ " "; } }
sub align($column_width, $word, $aligment = @*ARGS[0]) {
my $lr = $column_width - $word.chars;
my $c = $lr / 2;
given ($aligment) {
when "center" { " " x $c.ceiling ~ $word ~ " " x $c.floor }
when "right" { " " x $lr ~ $word }
default { $word ~ " " x $lr }
}
}</syntaxhighlight>
Or a more functional version, called like <code>./align.p6 left input.txt</code>, which however only supports left and right alignment (not center):
<syntaxhighlight lang="raku" line>sub MAIN ($alignment where 'left'|'right', $file) {
my @lines := $file.IO.lines.map(*.split('$').cache).cache;
my @widths = roundrobin(|@lines).map(*».chars.max);
my $align = {left=>'-', right=>''}{$alignment};
my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n";
printf $format, |$_ for @lines;
}</syntaxhighlight>
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
Dim MText as QMemorystream
MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
Line 5,281 ⟶ 8,156:
TextCenter = TextCenter + Newline
next
</syntaxhighlight>
{{out}}
<pre style="height:20ex;overflow:scroll">TextLeft contains:
Line 5,309 ⟶ 8,184:
=={{header|REBOL}}==
<
Title: "Align Columns"
URL: http://rosettacode.org/wiki/Align_columns
]
Line 5,368 ⟶ 8,241:
foreach i [left centre right] [
print ["^/Align" i "...^/"] entable data get i]
</syntaxhighlight>
{{out}}
Line 5,398 ⟶ 8,271:
justified, right justified, or center justified within its column.
</pre>
=={{header|Red}}==
<
Title: "Align Columns"
Original-Author: oofoe
Line 5,459 ⟶ 8,331:
foreach i [left centre right] [
print [newline "Align" i "..." newline] entable data get i]</
=={{header|REXX}}==
===(no output)===
<
z.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
z.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
Line 5,511 ⟶ 8,383:
end
say out
end</
===(with output)===
<
t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
t.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
t.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
t.
t.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
t.6 = "justified,$right$justified,$or$center$justified$within$its$column."
do r=1 while t.r\=='' /* [↓] process all the text lines. */
_=
cols= max(cols, c)
end /*r*/
do k=1 for cols; size= size + wid.k; end /*find the width of the biggest line. */
rows= r - 1 /*adjust ROWS because of the DO loop.*/
do j=1 for 3; say; say /*show
say center(word('left right center', j) "aligned", size+cols-1, "═") /*show title*/
do r=1 for rows; _= /*construct row by row. */
if j==
if j==
say substr(_, 2)
end /*j*/
{{out|output|text= when using the default input:}}
<pre>
══════════════════════════════════════════════left aligned══════════════════════════════════════════════
Line 5,578 ⟶ 8,446:
===(boxed output)===
Note:
<
t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
t.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
t.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
t.
t.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
t.6 = "justified,$right$justified,$or$center$justified$within$its$column."
do r=1 while t.r\=='' /* [↓] process all the text lines. */
_=
cols= max(cols, c)
end /*r*/
do k=1 for cols; size= size + wid.k; end /*find the width of the biggest line. */
rows= r - 1 /*adjust ROWS because of the DO loop.*/
do j=1 for 3; say; say /*show
say center(word('left right center', j) "aligned", size+cols+1, "═") /*show title*/
do r=0 to rows; _=; != '│'; if r==0 then != '┬'
do c=1 for cols; x= @.r.c
if r==0 then x= copies("─", wid.c + 1)
if j==1 then _= _ || ! || left(x, wid.c) /*justify left*/
if j==2 then _= _ || ! || right(x, wid.c) /* " ruggt*/
if j==3 then _= _ || ! ||
end /*c*/
if r==0 then do; _= '┌'substr(_, 2, length(_) - 1)"┐" /*top line.*/
bot= '└'substr(_, 2, length(_) - 2)"┘" /*bot " */
end
else _= _ || ! /*append trailing end boxing character.*/
say _
end /*r*/ /* [↑] shows words in boxes. */
say translate(bot, '┴',
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text= when using the default input:}}
<pre>
═══════════════════════════════════════════════left aligned═══════════════════════════════════════════════
Line 5,656 ⟶ 8,521:
=={{header|Ruby}}==
{{works with|Ruby|1.9.3+}}
<
=begin
Line 5,699 ⟶ 8,564:
puts aligner(infile, align)
end
</syntaxhighlight>
{{out}}
Line 5,729 ⟶ 8,594:
=={{header|Run BASIC}}==
<
+ "are$delineated$by$a$single$'dollar'$character,$write$a$program" _
+ "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"_
Line 5,767 ⟶ 8,632:
wend
print
end function</
{{out}}
<pre style="height:15ex;overflow:scroll">------------ align:left -- across:6 ------------
Line 5,807 ⟶ 8,672:
=={{header|Rust}}==
<
enum AlignmentType {
Left,
Center,
Right,
}
fn get_column_widths(text: &str) -> Vec<usize> {
let mut widths = Vec::new();
for line in text
.lines()
.map(|s| s.trim_matches(' ').trim_end_matches('$'))
{
let lens = line.split('$').map(|s| s.chars().count());
for
if idx < widths.len() {
widths[idx] = std::cmp::max(widths[idx], len);
} else {
widths.push(len);
}
Line 5,830 ⟶ 8,701:
let widths = get_column_widths(text);
let mut result = String::new();
for line in text
.lines()
.map(|s| s.trim_matches(' ').trim_end_matches('$'))
{
for (s, w) in line.split('$').zip(widths.iter()) {
let blank_count = w - s.chars().count();
Line 5,861 ⟶ 8,735:
println!("{}", repeat('-').take(110).collect::<String>());
println!("{}", align_columns(text, AlignmentType::Right));
}</
{{out}}
<pre style="height:15ex;overflow:scroll">
Line 5,893 ⟶ 8,767:
For Scala 2.7, change from fromPath to fromFile, and remove the extra parameter to Source's getLines.
<
val eol = System.getProperty("line.separator")
def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
Line 5,920 ⟶ 8,794:
alignFile(filename, alignment) foreach println
}
}</
Another take:
<
val padsize = (i-s.length).max(0)
d match {
Line 5,945 ⟶ 8,819:
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
padded map (_.reduceLeft(_ + _)) foreach println</
=={{header|Scheme}}==
<
(import (scheme base)
(scheme write)
Line 6,003 ⟶ 8,877:
(align-columns *example* 'center)
(align-columns *example* 'right)
</syntaxhighlight>
{{out}}
Line 6,032 ⟶ 8,906:
</pre>
=={{header|sed}}==
The code allows to left (by default) or right justify colums. Centering is not supported. Requires about 2x<size of input> bytes of memory (each line duplicated).
<
#!/bin/sed -nrf
# Format: <master-pattern>\n<line1>\n<line1-as-pattern>\n<line2>\n<line2-as-pattern>...
Line 6,112 ⟶ 8,985:
bnextline
}
</syntaxhighlight>
Example:
<pre>
Line 6,132 ⟶ 9,005:
=={{header|Seed7}}==
<
const array string: inputLines is [] (
Line 6,183 ⟶ 9,056:
writeln;
end for;
end func;</
{{out}}
Line 6,194 ⟶ 9,067:
justified, right justified, or center justified within its column.
</pre>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program align;
magic := false; $ turn off regexp matching in GNU SETL
read_file;
ncols := max/[#line : line in lines];
sizes := [1+max/[#(line(col) ? "") : line in lines] : col in [1..ncols]];
loop for line in lines do
print(+/[align(line(col), sizes(col)) : col in [1..#line]]);
end loop;
read_file::
f := open(command_line(1), "r");
lines := [];
loop doing geta(f, line); while line /= om do
lines with:= split(line, "$");
end loop;
close(f);
proc align(s, n);
case command_line(2) of
("r"): return lpad(s, n);
("l"): return rpad(s, n);
("c"): return center(s, n);
end case;
end proc;
proc center(s, n);
padding := n - #s;
l := " " * ceil(padding/2);
r := " " * floor(padding/2);
return l + s + r;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>$ setl align.setl test.txt l
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
$ setl align.setl test.txt r
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
$ setl align.setl test.txt c
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|Shiny}}==
<
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
Line 6,234 ⟶ 9,165:
align text 'left'
align text 'center'
align text 'right'</
<pre>Given a text file of many lines, where fields within a line
Line 6,258 ⟶ 9,189:
=={{header|Sidef}}==
<
method align(j) {
text.map { |row|
Line 6,304 ⟶ 9,235:
say f.align(left);
say f.align(middle);
say f.align(right);</
=={{Header|Smalltalk}}==
the following works with Smalltalk/X, but should also in other dialects (may have to add "centerPadded" to the String class).
{{works with |Smalltalk/X }}
<syntaxhighlight lang="smalltalk">text :=
'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$''dollar''$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
'.
printSep :=
[:colLengths |
Stdout nextPut:$+.
colLengths do:[:len | Stdout next:len put:$-; nextPut:$+ ].
Stdout cr.
].
printRows :=
[:text :box :justifyEach |
lines := StringCollection fromString:text.
rowSet := lines collect:[:line | line splitBy:$$ ].
maxNumCols := (rowSet collect:[:row | row size]) max.
maxLengths := rowSet
inject:(Array new:maxNumCols withAll:0)
into:[:maxesSoFar :row|
maxesSoFar
with:(row paddedTo:maxNumCols with:'')
collect:[:maxLen :col | maxLen max: col size]].
rowSet do:[:row |
|first|
box ifTrue:[ printSep value:maxLengths ].
first := true.
(box ifTrue:[row paddedTo:maxLengths size with:''] ifFalse:[row])
with: (box ifTrue:[maxLengths] ifFalse:[maxLengths to:row size])
do:[:col :len |
first ifTrue:[ box ifTrue:[Stdout nextPutAll:'|']. first := false.].
Stdout print:(justifyEach value:col value:len).
Stdout nextPutAll:(box ifTrue:'|' ifFalse:' ')
].
Stdout cr.
].
box ifTrue:[ printSep value:maxLengths ].
].
printRightJustified :=
[:text :box | printRows value:text value:box value:[:col :len | (col leftPaddedTo:len)]].
printLeftJustified :=
[:text :box | printRows value:text value:box value:[:col :len | (col paddedTo:len)]].
printCentered :=
[:text :box | printRows value:text value:box value:[:col :len | col centerPaddedTo:len]].
Stdout printCR:'Left justified:'.
printLeftJustified value:text value:false.
Stdout cr; printCR:'Right justified:'.
printRightJustified value:text value:false.
Stdout cr; printCR:'Centered:'.
printCentered value:text value:false.
Stdout cr; printCR:'Left justified with box:'.
printLeftJustified value:text value:true.
Stdout cr; printCR:'Right justified with box:'.
printRightJustified value:text value:true.
Stdout cr; printCR:'Centered with box:'.
printCentered value:text value:true.</syntaxhighlight>
{{out}}
<pre>Left justified:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Right justified:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Centered:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Left justified with box:
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|Given |a |text |file |of |many |lines, |where |fields |within |a |line|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|are |delineated|by |a |single|'dollar' |character,|write |a |program| | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|that |aligns |each |column|of |fields |by |ensuring|that |words |in |each|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|column |are |separated |by |at |least |one |space. | | | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|Further, |allow |for |each |word |in |a |column |to |be |either|left|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|justified,|right |justified,|or |center|justified|within |its |column.| | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
Right justified with box:
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Given| a| text| file| of| many| lines,| where| fields| within| a|line|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| are|delineated| by| a|single| 'dollar'|character,| write| a|program| | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| that| aligns| each|column| of| fields| by|ensuring| that| words| in|each|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| column| are| separated| by| at| least| one| space.| | | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Further,| allow| for| each| word| in| a| column| to| be|either|left|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|justified,| right|justified,| or|center|justified| within| its|column.| | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
Centered with box:
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Given | a | text | file | of | many | lines, | where |fields |within | a |line|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| are |delineated| by | a |single|'dollar' |character,| write | a |program| | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| that | aligns | each |column| of | fields | by |ensuring| that | words | in |each|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| column | are |separated | by | at | least | one | space. | | | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
| Further, | allow | for | each | word | in | a | column | to | be |either|left|
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+
|justified,| right |justified,| or |center|justified| within | its |column.| | | |
+----------+----------+----------+------+------+---------+----------+--------+-------+-------+------+----+</pre>
=={{header|Snobol}}==
{{works with|Snobol|4}}
<syntaxhighlight lang="snobol">* Since we don't know how much text we'll be reading in,
* we store the words and field widths in tables
Words = TABLE()
Widths = TABLE()
* Match text from start of string to the first dollar sign
WordPat = POS(0) BREAK('$') . Word LEN(1) REM . Rest
* We output the results aligned three different ways; these are the
* labels for those sections of output:
Labels = ARRAY(3)
Labels<1> = "Left-justified"
Labels<2> = "Right-justified"
Labels<3> = "Centered"
* There are built-in functions for left- and right- justification,
* but not necessarily one for centering (depending on
* implementation). So we define one.
DEFINE('CPAD(Word,Width)Z,Left') :(END_CPAD)
CPAD Z = SIZE(Word)
Left = Z + (Width - Z) / 2
CPAD = RPAD(LPAD(Word, Left), Width) :(RETURN)
END_CPAD
* Read in our text a line at a time and split into words on '$'
InLineLoop Line = INPUT :F(DoneReading)
LineCount = LineCount + 1
Column = 0
InWordLoop Column = Column + 1
* Separate Line into Word, Line=Rest at first dollar sign
Line WordPat = Rest :S(CheckMax)
* If there was no '$', the whole line is the next word
Word = Line
Line =
* Keep track of the largest number of columns on any line
CheckMax LE(Column, MaxColumn) :S(StoreWord)
MaxColumn = Column
StoreWord Words<LineCount ',' Column> = Word
* And the size of the longest word in each column
GT(SIZE(Word),Widths<Column>) :F(NoNewMaxWidth)
Widths<Column> = SIZE(Word)
* Loop if the line isn't empty yet
NoNewMaxWidth GT(Size(Line)) :S(InWordLoop) F(InLineLoop)
DoneReading
* Now we print the results out in the three justification styles
Style = 0
StyleLoop Style = Style + 1
GT(Style, 3) :S(END)
OUTPUT =
OUTPUT = Labels<Style> ':'
I = 0
OutLineLoop I = I + 1
GT(I, LineCount) :S(StyleLoop)
* Build up the output line by fields starting with the null string
Line =
J = 0
OutWordLoop J = J + 1
GT(J, MaxColumn) :S(PrintLine)
Word = Words<I ',' J>
GT(SIZE(Word)) :F(PrintLine)
* Place the word within the column according to the pass we're on
EQ(Style, 1) :F(NotLeft)
* Left-justified
Word = RPAD(Word, Widths<J>) :(AddWord)
NotLeft EQ(Style, 2) :F(NotRight)
* Right-justified
Word = LPAD(Word, Widths<J>) :(AddWord)
* Centered
NotRight Word = CPAD(Word, Widths<J>)
* Add word to line and loop
AddWord Line = Line GT(SIZE(Line)) ' '
Line = Line Word :(OutWordLoop)
* Print the line
PrintLine OUTPUT = Line :(OutLineLoop)
END
</syntaxhighlight>
{{Out}}
<pre>
Left-justified:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Right-justified:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Centered:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "aligncols" )
@( description, "Given a text file of many lines, where fields within a line are delineated ")
@( description, "by a single 'dollar' character, write a program that aligns each column of" )
@( description, "fields by ensuring that words in each column are separated by at least one" )
@( description, "space. Further, allow for each word in a column to be either left justified," )
@( description, "right justified, or center justified within its column. " )
@( description, "A modified version of the Ada solution from Rosetta Code" )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Align_columns" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure aligncols is
Text : constant string :=
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & ASCII.NUL &
"are$delineated$by$a$single$'dollar'$character,$write$a$program" & ASCII.NUL &
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & ASCII.NUL &
"column$are$separated$by$at$least$one$space." & ASCII.NUL &
"Further,$allow$for$each$word$in$a$column$to$be$either$left$" & ASCII.NUL &
"justified,$right$justified,$or$center$justified$within$its$column." & ASCII.NUL;
File : file_type;
Width : array(1..1000) of natural;
ch : character;
Column : positive := 1;
Start : positive := 1;
type Alignment is ( Left, Center, Right );
s : string;
padding : natural;
begin
-- Zero Widths
for I in arrays.first( Width )..arrays.last( Width ) loop
Width(I) := 0;
end loop;
-- Determining the widths of columns
for I in 1..strings.length(Text) loop
ch := strings.element( Text, I );
case ch is
when '$' | ASCII.NUL =>
Width (Column) := numerics.max(Width (Column), I - Start + 1);
Start := I + 1;
if strings.element( Text, I ) = ASCII.NUL then
Column := 1;
else
Column := @+1;
end if;
when others =>
null;
end case;
end loop;
create( File, out_file, "columned.txt" );
-- Formatting
for Align in Left..Right loop
Column := 1;
Start := 1;
for I in 1..strings.length(Text) loop
ch := strings.element( Text, I );
case ch is
when '$' | ASCII.NUL =>
s := strings.slice( Text, Start, I-1 );
padding := (Width( Column ) - strings.length(s));
case Align is
when Left =>
s := @ & (padding * ' ');
when Center =>
declare
left_padding : constant natural := padding/2;
right_padding : constant natural := padding - left_padding;
begin
s := (left_padding * ' ') & @ & (right_padding * ' ');
end;
when Right =>
s := (padding * ' ') & @;
when others =>
null;
end case;
put( File, s );
Start := I+1;
if ch = ASCII.NUL then
new_line( File );
Column := 1;
else
Column := @+1;
end if;
when others =>
null;
end case;
end loop;
new_line( File );
end loop;
close( File );
end aligncols;</syntaxhighlight>
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">fun curry f x y = f (x, y)
fun uncurry f (x, y) = f x y
fun maxWidths ([], widths) = widths
| maxWidths (strings, []) = map size strings
| maxWidths (s :: ss, w :: ws) = Int.max (size s, w) :: maxWidths (ss, ws)
val alignL = uncurry (StringCvt.padRight #" ")
and alignR = uncurry (StringCvt.padLeft #" ")
fun alignC (w, s) =
alignL (w, alignR ((w + size s) div 2, s))
fun formatTable tab =
let
val columnWidths = foldl maxWidths [] tab
in
fn f => String.concatWith "\n"
(map (String.concatWith " " o curry (ListPair.map f) columnWidths) tab)
end
val readTable =
map (String.fields (curry op= #"$"))
o String.tokens (curry op= #"\n")
o TextIO.inputAll
(* test stdin with all alignments *)
val () = print (String.concatWith "\n\n"
(map (formatTable (readTable TextIO.stdIn)) [alignL, alignC, alignR]) ^ "\n")</syntaxhighlight>
{{out}}
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Swift}}==
{{trans|Rust}}
<syntaxhighlight lang="swift">import Foundation
extension String {
func dropLastIf(_ char: Character) -> String {
if last == char {
return String(dropLast())
} else {
return self
}
}
}
enum Align {
case left, center, right
}
func getLines(input: String) -> [String] {
input
.components(separatedBy: "\n")
.map({ $0.replacingOccurrences(of: " ", with: "").dropLastIf("$") })
}
func getColWidths(from: String) -> [Int] {
var widths = [Int]()
let lines = getLines(input: from)
for line in lines {
let lens = line.components(separatedBy: "$").map({ $0.count })
for (i, len) in lens.enumerated() {
if i < widths.count {
widths[i] = max(widths[i], len)
} else {
widths.append(len)
}
}
}
return widths
}
func alignCols(input: String, align: Align = .left) -> String {
let widths = getColWidths(from: input)
let lines = getLines(input: input)
var res = ""
for line in lines {
for (str, width) in zip(line.components(separatedBy: "$"), widths) {
let blanks = width - str.count
let pre: Int, post: Int
switch align {
case .left:
(pre, post) = (0, blanks)
case .center:
(pre, post) = (blanks / 2, (blanks + 1) / 2)
case .right:
(pre, post) = (blanks, 0)
}
res += String(repeating: " ", count: pre)
res += str
res += String(repeating: " ", count: post)
res += " "
}
res += "\n"
}
return res
}
let input = """
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
"""
print(alignCols(input: input))
print()
print(alignCols(input: input, align: .center))
print()
print(alignCols(input: input, align: .right))</syntaxhighlight>
{{out}}
<pre style="height: 25em; overflow: scroll">Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. </pre>
=={{header|Tcl}}==
<
set text {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
Line 6,354 ⟶ 9,818:
}
puts ""
}</
{{out}}
<pre>Given a text file of many lines, where fields within a line
Line 6,376 ⟶ 9,840:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|Transd}}==
Transd has built-in support for "left" and "right" formatting, but not "centered", which added quite a bit of code.
<syntaxhighlight lang="scheme">#lang transd
MainModule : {
txt:
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.",
tabl: Table(),
n: 0,
colWidths: Vector<Int>(),
print: (λ centered Bool(false)
(for n in Seq(0 (num-rows tabl)) do
(with row (get-row tabl n)
(for m in Seq(0 (num-cols tabl)) do
(with wid (+ 1.0 (get colWidths @idx))
word (get row m) wl 0.0 lef 0
(if centered (= wl (size String(word))) (= lef (/ (- wid wl) 2.0))
(textout width: lef "" width: wl word width: (- wid (+ wl lef)) "")
else
(textout width: wid (get row m)))))
(lout ""))
)
),
_start: (λ
(load-table tabl txt fieldSep: "$" :emptyEls)
(for i in Seq(0 (num-cols tabl)) do (= n 0)
(tsd-query tabl
reduce: [i]
as: [[String()]]
using: (λ (set n (max (size (get @row 0)) n))))
(append colWidths n)
)
(textout :right "") (print)
(lout :left "") (print)
(lout "") (print true)
)
}</syntaxhighlight>{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program a line
that aligns each column of fields by ensuring that words in each
column are separated by at least one space. that words in each
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. be either left
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program a line
that aligns each column of fields by ensuring that words in each
column are separated by at least one space. that words in each
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. be either left
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program a line
that aligns each column of fields by ensuring that words in each
column are separated by at least one space. that words in each
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column. be either left
</pre>
=={{header|TSE SAL}}==
<syntaxhighlight lang="tsesal">
INTEGER PROC FNBlockChangeColumnAlignLeftB( INTEGER columnTotalI, INTEGER spaceTotalI, INTEGER buffer1I )
INTEGER B = FALSE
INTEGER downB = TRUE
INTEGER minI = 1
INTEGER I = 0
INTEGER J = 0
INTEGER K = 0
INTEGER L = 0
INTEGER buffer2I = 0
STRING s[255] = ""
INTEGER wordRightB = FALSE
STRING s1[255] = Query( WordSet )
IF ( NOT ( IsBlockInCurrFile() ) ) Warn( "Please mark a block" ) B = FALSE RETURN( B ) ENDIF // return from the current procedure if no block is marked
Set( BREAK, ON )
PushPosition()
PushBlock()
Set( WordSet, ChrSet( "a-zA-Z0-9_,." ) )
PushPosition()
buffer2I = CreateTempBuffer()
PopPosition()
PushPosition()
PushBlock()
DO 100 TIMES
AddLine( "", buffer2I )
ENDDO
PopBlock()
PopPosition()
GotoBlockBegin()
I = minI - 1
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
BegLine()
REPEAT
s = GetWord()
IF NOT ( s == "" )
s = Trim( s )
I = I + 1
IF ( I > columnTotalI )
I = minI
ENDIF
J = Length( s )
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
GotoLine( I )
//
IF ( CurrLineLen() == 0 )
BegLine()
InsertText( Format( Str( J ), " " ), _INSERT_ )
ELSE
K = Val( Trim( GetText( 1, MAXSTRINGLEN ) ) )
IF ( J > K )
BegLine()
DelToEol()
BegLine()
InsertText( Str( J ), _INSERT_ )
ENDIF
ENDIF
PopBlock()
PopPosition()
wordRightB = WordRight()
ENDIF
UNTIL ( s == "" ) OR ( NOT wordRightB )
ENDIF
downB = Down()
ENDWHILE
GotoBlockBegin()
I = minI - 1
L = 1
K = 1
WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
IF NOT LFind( "^$", "cgx" )
BegLine()
REPEAT
B = FALSE
s = GetWord()
IF NOT ( s == "" )
s = Trim( s )
I = I + 1
IF ( I > columnTotalI )
I = minI
K = 1
L = L + 1
ENDIF
//
PushPosition()
PushBlock()
GotoBufferId( buffer2I )
GotoLine( I )
J = Val( Trim( GetText( 1, MAXSTRINGLEN ) ) )
PopPosition()
PopBlock()
PushPosition()
PushBlock()
GotoBufferId( buffer1I )
GotoLine( L )
GotoColumn( K )
InsertText( s, _INSERT_ )
K = K + J + spaceTotalI
PopBlock()
PopPosition()
wordRightB = WordRight()
ENDIF
UNTIL ( s == "" ) OR ( NOT wordRightB )
ENDIF
AddLine( "", buffer1I )
downB = Down()
ENDWHILE
OneWindow()
VWindow()
GotoWindow( 1 )
GotoBufferId( buffer2I )
GotoWindow( 2 )
GotoBufferId( buffer1I )
B = TRUE
Set( WordSet, s1 )
PopPosition()
PopBlock()
RETURN( B )
END
//
PROC Main()
STRING s1[255] = "12" // change this
STRING s2[255] = "2" // change this
INTEGER bufferI = 0
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
IF ( NOT ( Ask( "block: change: column: align: left: columnTotalI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
IF ( NOT ( Ask( "block: change: column: align: left: spaceTotalI = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
Message( FNBlockChangeColumnAlignLeftB( Val( s1 ), Val( s2 ), bufferI ) ) // gives e.g. TRUE
GotoBufferId( bufferI )
END
</syntaxhighlight>
{{out}} <pre>
Given a text file of many lines, where fields within a line
are delineated by a single dollar character, write a program that aligns
each column of fields by ensuring that words in each column are
separated by at least one space. Further, allow for each word in
a column to be either left justified, right justified, or center justified
within its column.
</pre>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
MODE DATA
Line 6,401 ⟶ 10,079:
ENDLOOP
SET exampletext=JOIN(new1,"$",new2,new3,new4,new5,new6,new7,new8,new9,new10,new11,new12)
</syntaxhighlight>
{{out}}
<pre>
Line 6,415 ⟶ 10,093:
=={{header|TXR}}==
<
@ (coll)@{item /[^$]+/}@(end)
@(end)
Line 6,441 ⟶ 10,119:
@{pi @(- [cw i] (trunc (- [cw i] (length pi)) 2))} @(end)
@ (end)
@(end)</
<pre>$ txr align-columns.txr align-columns.dat
Line 6,465 ⟶ 10,143:
=={{header|UNIX Shell}}==
This is a draft implementation of the "align columns" problem using Unix shell commands. The key tool for left and right justified text is the "rs" command. Centered text is a little more complex, since this is not a feature currently in "rs" (''The centered solution will be added later.'')
<
cat <<EOF_OUTER > just-nocenter.sh
#!/bin/sh
Line 6,503 ⟶ 10,181:
exit
EOF_OUTER
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="sh">
$ ./just-nocenter.sh
Given a text file of many lines, where fields within a line
Line 6,520 ⟶ 10,198:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</syntaxhighlight>
The centered output will be added later, when I've more time. '' I did this in about 10 minutes.''
=== Using <tt>column(1)</tt> ===
Note that the left-justified case can be handled trivially by the <tt>column</tt> command, which ships with modern Linux and macOS systems:
<syntaxhighlight lang="sh">tr '$' ' ' | column -t</syntaxhighlight>
{{Out}}
<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|Ursala}}==
Line 6,531 ⟶ 10,222:
For right justification, each word's string of trailing blanks is moved to the beginning,
and for center justification, the trailing blanks are divided equally between the beginning and end of each word.
<
text =
Line 6,550 ⟶ 10,241:
#show+
main = mat0 <.just_left,just_center,just_right> text</
{{out}}
<pre style="height:17ex;overflow:scroll">
Line 6,579 ⟶ 10,270:
Both arguments are optional and default to "left" and 1 respectively.
<syntaxhighlight lang="vb">
Public Sub TestSplit(Optional align As String = "left", Optional spacing As Integer = 1)
Dim word() As String
Line 6,645 ⟶ 10,336:
Next l
End Sub
</syntaxhighlight>
{{out}}
Line 6,665 ⟶ 10,356:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|VBScript}}==
{{trans|Rexx}}
<syntaxhighlight lang="vb">' Align columns - RC - VBScript
Const nr=16, nc=16
ReDim d(nc),t(nr), wor(nr,nc)
i=i+1: t(i) = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
i=i+1: t(i) = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
i=i+1: t(i) = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
i=i+1: t(i) = "column$are$separated$by$at$least$one$space."
i=i+1: t(i) = "Further,$allow$for$each$word$in$a$column$To$be$either$left$"
i=i+1: t(i) = "justified,$right$justified,$or$center$justified$within$its$column."
For r=1 to nr
If t(r)="" Then Exit For
w=xRTrim(t(r),"$")
m=Split(w,"$")
For c=1 To UBound(m)+1
wor(r,c)=m(c-1)
If Len(wor(r,c))>d(c) Then d(c)=Len(wor(r,c))
Next 'c
If c>cols Then cols=c
Next 'r
rows=r-1
tt=Array("Left","Right","Center")
For n=1 To 3
Wscript.Echo
Wscript.Echo "*****" & tt(n-1) & "*****"
For r=1 To rows
w=""
For c=1 To cols
x=wor(r,c): s=Space(d(c))
Select Case n
Case 1: w=w &" "& Left (x & s,d(c))
Case 2: w=w &" "& Right (s & x,d(c))
Case 3: w=w &" "& xCentre(x,d(c)," ")
End Select 'n
Next 'c
Wscript.Echo Mid(w,2)
Next 'r
Next 'n
Function xCentre(c, n, Pad)
Dim j
If n > Len(c) Then
j = (n - Len(c)) \ 2
If (n - Len(c)) Mod 2 <> 0 Then j = j + 1
xCentre = Mid(String(j, Pad) & c & String(j, Pad), 1, n)
Else
xCentre = c
End If
End Function 'xCentre
Function xRTrim(c, Pad)
Dim i2, l, cc
cc = "": l = Len(c)
If l > 0 Then
i2 = l
Do While (Mid(c, i2, 1) = Pad And i2 > 1)
i2 = i2 - 1
Loop
If i2 = 1 And Mid(c, i2, 1) = Pad Then i2 = 0
If i2 > 0 Then cc = Mid(c, 1, i2)
End If
xRTrim = cc
End Function 'xRTrim
</syntaxhighlight>
{{out}}
<pre>
*****Left*****
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column To be either left
justified, right justified, or center justified within its column.
*****Right*****
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column To be either left
justified, right justified, or center justified within its column.
*****Center*****
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column To be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Vedit macro language}}==
This implementation converts the file currently being edited. The file can then be saved with different filename if required.
<
#11 = 1 // Align: 1 = left, 2 = center, 3 = right
Line 6,708 ⟶ 10,491:
}
Line(1, ERRBREAK)
}</
{{out}}
Line 6,736 ⟶ 10,519:
=={{header|Visual Basic}}==
<
Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)
Line 6,751 ⟶ 10,534:
Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf);
Next i, j
End Sub</
Usage:<
Const Text$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & vbLf & _
"are$delineated$by$a$single$'dollar'$character,$write$a$program" & vbLf & _
Line 6,763 ⟶ 10,546:
Debug.Print vbLf; "-- Center:": AlignCols Split(Text, vbLf), vbCenter
Debug.Print vbLf; "-- Right:": AlignCols Split(Text, vbLf), vbRightJustify
End Sub</
{{out}}
<pre>-- Left:
Line 6,790 ⟶ 10,573:
=={{header|Visual Basic .NET}}==
<
Private Delegate Function Justification(s As String, width As Integer) As String
Line 6,854 ⟶ 10,637:
End Sub
End Module</
{{out}}
Line 6,880 ⟶ 10,663:
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>
=={{header|V (Vlang)}}==
Currently (5/2022) V (Vlang) uses string interpolation so `$` have to be escaped. Variables in formatting aren't currently allowed, and if they were only right/left are currently valid options
<syntaxhighlight lang="v (vlang)">
const text = "Given\$a\$text\$file\$of\$many\$lines,\$where\$fields\$within\$a\$line\$
are\$delineated\$by\$a\$single\$'dollar'\$character,\$write\$a\$program
that\$aligns\$each\$column\$of\$fields\$by\$ensuring\$that\$words\$in\$each\$
column\$are\$separated\$by\$at\$least\$one\$space.
Further,\$allow\$for\$each\$word\$in\$a\$column\$to\$be\$either\$left\$
justified,\$right\$justified,\$or\$center\$justified\$within\$its\$column."
struct Formatter {
mut:
text [][]string
width []int
}
fn new_formatter(text string) Formatter {
mut f := Formatter{}
for line in text.split_into_lines() {
mut words := line.split("\$")
for words[words.len-1] == "" {
words = words[..words.len-1]
}
f.text << words
for i, word in words {
if i == f.width.len {
f.width << word.len
} else if word.len > f.width[i] {
f.width[i] = word.len
}
}
}
return f
}
enum Justify {
left = 0
middle
right
}
fn (f Formatter) print(j Justify) {
for line in f.text {
for i, word in line {
match j {
.left {
print('$word${' '.repeat(f.width[i]-word.len)} ')
}
.middle {
mut extra := 0
if (f.width[i]%2==1 && word.len%2==0) || (f.width[i]%2==0 && word.len%2==1) {
extra++
}
print('${' '.repeat((f.width[i]-word.len)/2)}$word${' '.repeat((f.width[i]-word.len)/2+extra)} ')
}
.right {
print('${' '.repeat(f.width[i]-word.len)}$word ')
}
}
}
println("")
}
println("")
}
fn main() {
f := new_formatter(text)
f.print(Justify.left)
f.print(Justify.middle)
f.print(Justify.right)
}</syntaxhighlight>
{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "io" for File
import "./fmt" for Fmt
var LEFT = 0
var RIGHT = 1
var CENTER = 2
var justStrs = ["LEFT", "RIGHT", "CENTER"]
// Gets a list of lines in the file with each line split into fields.
var getLines = Fn.new { |fileName|
var contents = File.read(fileName)
var lines = contents.split("\n") // use "\r\n" on Windows
for (i in 0...lines.count) {
lines[i] = lines[i].trim().trimEnd("$")
if (lines[i] == "") { // get rid of final blank line, if any
lines = lines[0..-2]
break
}
lines[i] = lines[i].split("$")
}
return lines
}
var alignCols = Fn.new { |lines, just|
// find maximum number of columns
var nCols = lines.reduce(0) { |acc, line| (line.count > acc) ? line.count : acc }
// find maximum width for each column
var maxWids = List.filled(nCols, 0)
for (line in lines) {
for (i in 0...line.count) {
var width = line[i].count
if (width > maxWids[i]) maxWids[i] = width
}
}
System.print("With %(justStrs[just]) justification:")
for (line in lines) {
for (i in 0...line.count) {
var width = maxWids[i] + 1
if (just == LEFT) {
System.write(Fmt.s(-width, line[i]))
} else if (just == RIGHT) {
System.write(Fmt.s(width, line[i]))
} else if (just == CENTER) {
System.write(Fmt.m(width, line[i]))
}
}
System.print()
}
System.print()
}
var fileName = "align_cols.txt"
var lines = getLines.call(fileName)
for (i in 0..2) alignCols.call(lines, i)</syntaxhighlight>
{{out}}
<pre>
With LEFT justification:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
With RIGHT justification:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
With CENTER justification:
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">
string 0;
def LF=$0A, CR=$0D;
def Left, Right, Center;
proc AlignCols(S); \Display string S with its columns aligned
char S, C, Field(80), ColWidth(80);
int I, J, N, Just;
proc Justify;
int T;
proc SpOut(M); \Output M space characters
int M, K;
for K:= 0 to M-1 do ChOut(0, ^ );
proc FieldOut; \Output Field of N characters
int K;
for K:= 0 to N-1 do ChOut(0, Field(K));
[case Just of
Left: [FieldOut(N); SpOut(ColWidth(J)-N+1)];
Right: [SpOut(ColWidth(J)-N+1); FieldOut(N)];
Center:[T:= ColWidth(J)-N+1;
SpOut(T/2); FieldOut(N); SpOut(T/2 + rem(0))]
other [];
];
[\Get width (in characters) of each column
for J:= 0 to 80-1 do ColWidth(J):= 0;
I:= 0; J:= 0; N:= 0;
loop [repeat C:= S(I); I:= I+1 until C # CR;
if N > ColWidth(J) then ColWidth(J):= N;
case C of
0: quit;
^$: [N:= 0; J:= J+1];
LF: [N:= 0; J:= J+1; J:= 0]
other N:= N+1;
];
for Just:= Left to Center do
[I:= 0; J:= 0; N:= 0;
loop [repeat C:= S(I); I:= I+1 until C # CR;
case C of
0: [Justify(Just); CrLf(0); quit];
^$: [Justify(Just); N:= 0; J:= J+1];
LF: [Justify(Just); CrLf(0); N:= 0; J:= 0]
other [Field(N):= C; N:= N+1];
];
CrLf(0);
];
];
AlignCols("Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.")
</syntaxhighlight>
{{out}}
<pre>
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.
</pre>
=={{header|Yabasic}}==
{{trans|Run BASIC}}
<syntaxhighlight lang="yabasic">theString$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
theString$ = theString$ + "are$delineated$by$a$single$'dollar'$character,$write$a$program"
theString$ = theString$ + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
theString$ = theString$ + "column$are$separated$by$at$least$one$space."
theString$ = theString$ + "Further,$allow$for$each$word$in$a$column$to$be$either$left$"
theString$ = theString$ + "justified,$right$justified,$or$center$justified$within$its$column."
x = shoTable(theString$, "left", 6)
x = shoTable(theString$, "right", 6)
x = shoTable(theString$, "center", 6)
end
sub word$(sr$, wn, delim$)
local i, j, n, sd, sl, sl2
local s$, res$, d$
d$ = delim$
j = wn
if j = 0 j = j+1
res$ = "" : s$ = sr$
if d$ = "" d$ = " "
sd = len(d$) : sl = len(s$)
do
n = instr(s$,d$)
j = j - 1
if j = 0 then
if n = 0 then res$ = s$ else res$ = mid$(s$, 1, n-1) : fi
return res$
fi
if n = 0 return res$
if n = sl-sd then res$ = "" : return res$ : fi
sl2 = sl-n
s$ = mid$(s$, n+1, sl2)
sl = sl2
loop
return res$
end sub
sub shoTable(theString$, align$, across)
local i, a$, b$
print "------------ align:", align$, " -- across:", across, " ------------"
dim siz(across)
b$ = " "
while word$(theString$, i+1, "$") <> ""
siz(mod(i, across)) = max(siz(mod(i, across)), len(word$(theString$, i+1, "$")))
i = i+1
wend
for i = 0 to across - 1
siz(i) = siz(i)+1
if siz(i) and 1 siz(i) = siz(i)+1
next i
i = 0
a$ = word$(theString$, i+1, "$")
while a$ <> ""
s = siz(mod(i, across)) - len(a$)
if align$ = "right" a$ = left$(b$, s) + a$
if align$ = "left" a$ = a$ + left$(b$, s)
if align$ = "center" a$ = left$(b$, int(s / 2)) + a$ + left$(b$, int(s / 2) + (s and 1))
print "|", a$;
i = i + 1
if mod(i, across) = 0 print "|"
a$ = word$(theString$, i+1, "$")
wend
print
end sub</syntaxhighlight>
{{out}}
<pre>Same as Run BASIC entry.</pre>
=={{header|zkl}}==
<
words:=text.split("$").apply("split").flatten();
max:=words.reduce(fcn(p,n){ n=n.len(); n>p and n or p },0);
Line 6,897 ⟶ 11,017:
do{ w.pump(wordsPerCol,d,fmt).append("\n") } while(not w.atEnd);
d.text;
}</
<
"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n"
"are$delineated$by$a$single$'dollar'$character,$write$a$program\n"
Line 6,908 ⟶ 11,028:
format(text,-1).print();
format(text, 0).print();
format(text, 1).print();</
Blow apart the text into a list of words, find max len of any word, calc how many words will fit on a 80 col line, format all words into a bit bucket line at a time. Formatting is "%-ms" or "%ms" for left & right justify (m is field width), calculated for center. fmt is the string format method or center calc function, depending. Where string formatting can be used, it would be better to format all words in a line in one go but the code would be longer.
{{out}}
Line 6,945 ⟶ 11,065:
=={{header|ZX Spectrum Basic}}==
The max width (without 'hack') of ZX Spectrum screen is 32 characters. The text sample is adapted for this feature.
<
10 DATA 6
20 DATA "The$problem$of$Speccy$"
Line 6,991 ⟶ 11,111:
3090 NEXT i
3095 PRINT
3100 RETURN</
{{out}}Left alignement example:
|