aboutsummaryrefslogtreecommitdiff
path: root/challenge-101/abigail/python/ch-1.py
blob: 22553ccb0bc8919364f7cdc59b8e022cede55e1b (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
#!/opt/local/bin/python

#
# See ../README.md
#

#
# Run as python ch-1.py < input-file
#

from math import floor, sqrt
import sys

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

#
# Fetch data
#
elements = input () . split ()

#
# Find the optimal width and height
#
count = len (elements)
height = floor (sqrt (count))
while count % height:
    height = height - 1

width = floor (count / height)


#
# Initialize the matrix
#
min_x = 0
max_x = height - 1
min_y = 0
max_y = width - 1

matrix = [[0] * width for x in range (height)]
    

#
# Fill the matrix, starting at the bottom left
#
x         = max_x
y         = min_y
direction = RIGHT
for element in elements:
    matrix [x] [y] = element
    turn = False
    if  direction == RIGHT:
        if  y >= max_y:
            turn = True; x = x - 1; max_x = max_x - 1
        else:
            y = y + 1

    if  direction == UP:
        if  x <= min_x:
            turn = True; y = y - 1; max_y = max_y - 1
        else:
            x = x - 1

    if  direction == LEFT:
        if  y <= min_y:
            turn = True; x = x + 1; min_x = min_x + 1
        else:
            y = y - 1

    if  direction == DOWN:
        if  x >= max_x:
            turn = True; y = y + 1; min_y = min_y + 1
        else:
            x = x + 1

    if  turn:
        direction = direction + 1
        direction = direction % 4


#
# Find the widths of each column
#
widths = [0] * width

for y in range (width):
    max = 0
    for x in range (height):
        if  max < len (matrix [x] [y]):
            max = len (matrix [x] [y])
    widths [y] = max


#
# Print the matrix
#
for x in range (height):
    for y in range (width):
        if  y > 0:
            sys . stdout . write (" ")
        #
        # Format the entry. Format will look something like '{:>Ws}',
        # where W is the width of the column.
        #
        sys . stdout . write (("{:>" + str (widths [y]) + "s}") .
                                format (matrix [x] [y]))
    sys . stdout . write ("\n")