This commit is contained in:
Ingy döt Net 2013-04-10 16:57:12 -07:00
parent 518da4a923
commit 764da6cbbb
6144 changed files with 83610 additions and 11 deletions

View file

@ -0,0 +1,74 @@
using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
// build input table and calculate columns count
string[][] table = new string[lines.Length][];
int columns = 0;
for (int i = 0; i < lines.Length; i++)
{
string[] row = lines[i].TrimEnd(Separator).Split(Separator);
if (columns < row.Length) columns = row.Length;
table[i] = row;
}
// create formatted table
string[][] formattedTable = new string[table.Length][];
for (int i = 0; i < formattedTable.Length; i++)
{
formattedTable[i] = new string[columns];
}
for (int j = 0; j < columns; j++)
{
// get max column width
int columnWidth = 0;
for (int i = 0; i < table.Length; i++)
{
if (j < table[i].Length && columnWidth < table[i][j].Length)
columnWidth = table[i][j].Length;
}
// justify column cells
for (int i = 0; i < formattedTable.Length; i++)
{
if (j < table[i].Length)
formattedTable[i][j] = justification(table[i][j], columnWidth);
else
formattedTable[i][j] = new String(' ', columnWidth);
}
}
// create result
string[] result = new string[formattedTable.Length];
for (int i = 0; i < result.Length; i++)
{
result[i] = String.Join(" ", formattedTable[i]);
}
return result;
}
static string JustifyLeft(string s, int width) { return s.PadRight(width); }
static string JustifyRight(string s, int width) { return s.PadLeft(width); }
static string JustifyCenter(string s, int width)
{
return s.PadLeft((width + s.Length) / 2).PadRight(width);
}
static void Main()
{
string[] 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.",
};
foreach (string line in AlignColumns(input, JustifyCenter))
{
Console.WriteLine(line);
}
}
}

View file

@ -0,0 +1,48 @@
(defun nonempty (seq)
(position-if (lambda (x) (declare (ignore x)) t) seq))
(defun split (delim seq)
"Splits seq on delim into a list of subsequences. Trailing empty
subsequences are removed."
(labels
((f (seq &aux (pos (position delim seq)))
(if pos
(cons
(subseq seq 0 pos)
(f (subseq seq (1+ pos))))
(list seq))))
(let* ((list (f seq))
(end (position-if #'nonempty list :from-end t)))
(subseq list 0 (1+ end)))))
(defun lengthen (list minlen filler-elem &aux (len (length list)))
"Destructively pads list with filler-elem up to minlen."
(if (< len minlen)
(nconc list (make-list (- minlen len) :initial-element filler-elem))
list))
(defun align-columns (text
&key (align :left)
&aux
(fmtmod (case align
(:left "@")
(:right ":")
(:center "@:")
(t (error "Invalid alignment."))))
(fields (mapcar (lambda (line) (split #\$ line))
(split #\Newline text)))
(mostcols (loop for l in fields
maximize (length l)))
widest)
(setf fields (mapcar (lambda (l) (lengthen l mostcols ""))
fields))
(setf widest (loop for col below (length (first fields))
collect (loop for row in fields
maximize (length (elt row col)))))
(format nil
(with-output-to-string (s)
(princ "~{~{" s)
(dolist (w widest)
(format s "~~~d~a<~~a~~>" (1+ w) fmtmod))
(princ "~}~%~}" s))
fields))

View file

@ -0,0 +1,23 @@
import std.stdio, std.string, std.algorithm, std.range;
void main() {
auto data =
"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."
.splitLines.map!q{ a.chomp("$").split("$") };
int[int] maxWidths;
foreach (line; data)
foreach (i, word; line)
maxWidths[i] = max(maxWidths.get(i, 0), word.length);
foreach (just; [&leftJustify!string, &center!string,
&rightJustify!string])
foreach (line; data)
writefln("%-(%s %)", iota(line.length)
.map!(i => just(line[i], maxWidths[i], ' ')));
}

View file

@ -0,0 +1,56 @@
USES
StdCtrls, Classes, SysUtils, StrUtils, Contnrs;
procedure AlignByColumn(Output: TMemo; 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, TempTString: TStringlist;
TextLines: TObjectList;
MaxLength, i, j: Byte;
OutPutString, EmptyString, Item: String;
begin
TRY
MaxLength := 0;
TextLines := TObjectList.Create(True);
TextLine := TStringList.Create;
TextLine.text := TextToAlign;
for i:= 0 to TextLine.Count - 1 do
begin
TempTString := TStringlist.create;
TempTString.text :=AnsiReplaceStr(TextLine[i], '$', #$D#$A);
TextLines.Add(TempTString);
end;
for i := 0 to TextLines.Count - 1 do
for j := 0 to TStringList(TextLines.Items[i]).Count - 1 do
If Length(TStringList(TextLines.Items[i])[j]) > MaxLength then
MaxLength := Length(TStringList(TextLines.Items[i])[j]);
If MaxLength > 0 then
MaxLength := MaxLength + 2; // Add to empty spaces to it
for i := 0 to TextLines.Count - 1 do
begin
OutPutString := '';
for j := 0 to TStringList(TextLines.Items[i]).Count - 1 do
begin
EmptyString := StringOfChar(' ', MaxLength);
Item := TStringList(TextLines.Items[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;
Output.Lines.Add(OutPutString);
end;
FINALLY
FreeAndNil(TextLine);
FreeAndNil(TextLines);
END;
end;

View file

@ -0,0 +1,29 @@
pragma.enable("accumulator")
def left(width, word) {
return word + " " * (width - word.size())
}
def center(width, word) {
def leftCount := (width - word.size()) // 2
return " " * leftCount + word + " " * (width - word.size() - leftCount)
}
def right(width, word) {
return " " * (width - word.size()) + word
}
def alignColumns(align, text) {
def split := accum [] for line in text.split("\n") { _.with(line.split("$")) }
var widths := []
for line in split {
for i => word in line {
widths with= (i, widths.fetch(i, fn{0}).max(word.size()))
}
}
return accum "" for line in split {
_ + accum "" for i => word in line {
_ + align(widths[i] + 1, word)
} + "\n"
}
}

View file

@ -0,0 +1,30 @@
? def 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."; null
? println(alignColumns(left, 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.
? println(alignColumns(center, 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.
? println(alignColumns(right, 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.

View file

@ -0,0 +1,61 @@
constant 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."
}
function split(sequence s, integer c)
sequence out
integer first, delim
out = {}
first = 1
while first<=length(s) do
delim = find_from(c,s,first)
if delim = 0 then
delim = length(s)+1
end if
out = append(out,s[first..delim-1])
first = delim + 1
end while
return out
end function
function align(sequence s, integer width, integer alignment)
integer n
n = width - length(s)
if n <= 0 then
return s
elsif alignment < 0 then
return s & repeat(' ', n)
elsif alignment > 0 then
return repeat(' ', n) & s
else
return repeat(' ', floor(n/2)) & s & repeat(' ', floor(n/2+0.5))
end if
end function
integer maxlen
sequence lines
maxlen = 0
lines = repeat(0,length(data))
for i = 1 to length(data) do
lines[i] = split(data[i],'$')
for j = 1 to length(lines[i]) do
if length(lines[i][j]) > maxlen then
maxlen = length(lines[i][j])
end if
end for
end for
for a = -1 to 1 do
for i = 1 to length(lines) do
for j = 1 to length(lines[i]) do
puts(1, align(lines[i][j],maxlen,a) & ' ')
end for
puts(1,'\n')
end for
puts(1,'\n')
end for