example: add some tasks of Rosetta code
[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 # Use `Text::justify` for 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 var max = 0
17 for line in text.split('\n') do
18 rows.add line.split("$")
19 end
20
21 # Compute the final length of each column
22 var lengths = new Array[Int]
23 for fields in rows do
24 var i = 0
25 for field in fields do
26 var fl = field.length
27 if lengths.length <= i or fl > lengths[i] then
28 lengths[i] = fl
29 end
30 i += 1
31 end
32 end
33
34 # Process each line and align each field
35 for fields in rows do
36 var line = new Array[String]
37 var i = 0
38 for field in fields do
39 line.add field.justify(lengths[i], left)
40 i += 1
41 end
42 print line.join(" ")
43 end
44 end
45
46 var text = """
47 Given$a$text$file$of$many$lines,$where$fields$within$a$line$
48 are$delineated$by$a$single$'dollar'$character,$write$a$program
49 that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
50 column$are$separated$by$at$least$one$space.
51 Further,$allow$for$each$word$in$a$column$to$be$either$left$
52 justified,$right$justified,$or$center$justified$within$its$column."""
53
54 aligner(text, 0.0)
55 aligner(text, 1.0)
56 aligner(text, 0.5)