aboutsummaryrefslogtreecommitdiff
path: root/challenge-101/abigail/ruby/ch-1.rb
blob: 4a383ab873836b6c562a2c7d1448aac395881f04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/ruby

#
# See ../README.md
#
 
#
# Run as: ruby ch-1.rb < input-file
#

RIGHT  = 0
UP     = 1
LEFT   = 2
DOWN   = 3

#
# Read the data, one line of input, split on whitespace.
#
elements = gets . chomp . split

#
# Calculate the optimal height and width
#
count  = elements . length
height = (Math . sqrt (count)) . floor
while count % height > 0
    height -= 1
end
width = count / height

#
# Initialize the matrix
#
matrix = Array . new (height)
for x in 0 .. height - 1 do
    matrix [x] = Array . new (width)
end


#
# Fill the matrix, starting from the bottom left.
#
min_x     = 0
max_x     = height - 1
min_y     = 0
max_y     = width  - 1
x         = max_x
y         = min_y
direction = RIGHT

for element in elements do
    matrix [x] [y] = element
    turn = false
    if  direction == RIGHT
        if   y >= max_y then turn = true; x -= 1; max_x -= 1
        else y += 1
        end
    end

    if  direction == UP
        if   x <= min_x then turn = true; y -= 1; max_y -= 1
        else x -= 1
        end
    end

    if  direction == LEFT
        if   y <= min_y then turn = true; x += 1; min_x += 1
        else y -= 1
        end
    end

    if  direction == DOWN
        if   x >= max_x then turn = true; y += 1; min_y += 1
        else x += 1
        end
    end

    if  turn
        direction += 1
        direction %= 4
    end

end

#
# Create an array with column widths
#
widths = Array . new (width)
for y in 0 .. width - 1 do
    max = 0
    for x in 0 .. height - 1 do
        if  max < matrix [x] [y] . length
            max = matrix [x] [y] . length
        end
    end
    widths [y] = max
end

#
# Pretty print the matrix
#
for x in 0 .. height - 1 do
    for y in 0 .. width - 1 do
        if  y > 0
            print " "
        end
        format = "%" + widths [y] . to_s + "s"
        printf format, matrix [x] [y]
    end
    print "\n"
end