24 lines
1.1 KiB
Text
24 lines
1.1 KiB
Text
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)
|