59 lines
1.8 KiB
Plaintext
59 lines
1.8 KiB
Plaintext
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)
|