rosettacode: Fix spelling mistakes
[nit.git] / examples / rosettacode / align_columns.nit
1 #!/usr/bin/env nit
2 #
3 # This file is part of NIT ( http://www.nitlanguage.org ).
4 # This program is public domain
5
6 # Task: Align columns
7 # SEE: <http://rosettacode.org/wiki/Align_columns>
8 #
9 # Uses `Text::justify` from the standard library.
10 module align_columns
11
12 fun aligner(text: String, left: Float)
13 do
14 # Each row is a sequence of fields
15 var rows = new Array[Array[String]]
16 for line in text.split('\n') do
17 rows.add line.split("$")
18 end
19
20 # Compute the final length of each column
21 var lengths = new Array[Int]
22 for fields in rows do
23 var i = 0
24 for field in fields do
25 var fl = field.length
26 if lengths.length <= i or fl > lengths[i] then
27 lengths[i] = fl
28 end
29 i += 1
30 end
31 end
32
33 # Process each line and align each field
34 for fields in rows do
35 var line = new Array[String]
36 var i = 0
37 for field in fields do
38 line.add field.justify(lengths[i], left)
39 i += 1
40 end
41 print line.join(" ")
42 end
43 end
44
45 var text = """
46 Given$a$text$file$of$many$lines,$where$fields$within$a$line$
47 are$delineated$by$a$single$'dollar'$character,$write$a$program
48 that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
49 column$are$separated$by$at$least$one$space.
50 Further,$allow$for$each$word$in$a$column$to$be$either$left$
51 justified,$right$justified,$or$center$justified$within$its$column."""
52
53 aligner(text, 0.0)
54 aligner(text, 1.0)
55 aligner(text, 0.5)