lib/core/stream: LineIterator use CachedIterator
[nit.git] / examples / rosettacode / zigzag_matrix.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: Zig-zag matrix
7 # SEE: <http://rosettacode.org/wiki/Zig-zag_matrix>
8
9 fun zig_zag(number: Int): Array[Array[Int]] do
10 var first_number = 0
11 var last_number = number * number - 1
12 # x: line position
13 # y: column position
14 var x = 0
15 var y = 0
16 # true: top-right
17 # false: bottom-left
18 var trajectory = true
19 # first array: column
20 # second array: line
21 var array = new Array[Array[Int]]
22 for i in [0..number[ do array.add(new Array[Int].filled_with(0, number))
23
24 while first_number <= last_number do
25 array[y][x] = first_number
26 array[number - y - 1][number - x - 1] = last_number
27
28 first_number += 1
29 last_number -= 1
30
31 if x == 0 and y == 0 then
32 x += 1
33 trajectory = false
34 else
35 if y == 0 and trajectory then
36 trajectory = false
37 x += 1
38 continue
39 end
40 if y == 0 and not trajectory then
41 x -= 1
42 y += 1
43 continue
44 end
45 if x == 0 and not trajectory then
46 trajectory = true
47 y += 1
48 continue
49 end
50 if x == 0 and trajectory then
51 x += 1
52 y -= 1
53 continue
54 end
55 if trajectory then
56 x += 1
57 y -= 1
58 else
59 x -= 1
60 y += 1
61 end
62 end
63 end
64 return array
65 end
66
67 var number = 10
68 var number_length_max = (number * number - 1).to_s.length
69 for line in zig_zag(number) do
70 for element in line do
71 printn element
72 var blank = number_length_max - element.to_s.length + 1
73 for x in blank.times do printn " "
74 end
75 print ""
76 end