2013-11-05 19:39:03 +01:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2015-11-20 23:12:22 +01:00
|
|
|
|
|
|
|
def print_arr(a):
|
2013-11-05 19:39:03 +01:00
|
|
|
for line in a:
|
|
|
|
print(line)
|
|
|
|
|
2015-11-20 23:12:22 +01:00
|
|
|
|
2013-11-05 19:39:03 +01:00
|
|
|
def initialise(n):
|
2015-11-20 23:12:22 +01:00
|
|
|
array = [[0 for j in xrange(0, n)] for i in xrange(0, n)]
|
2013-11-05 19:39:03 +01:00
|
|
|
return array
|
|
|
|
|
2015-11-20 23:12:22 +01:00
|
|
|
|
|
|
|
def spiral_fill(a):
|
2013-11-05 19:39:03 +01:00
|
|
|
n = len(a)
|
|
|
|
x = y = n/2
|
|
|
|
number = 1
|
2015-11-20 23:12:22 +01:00
|
|
|
# r u l o
|
|
|
|
order = [(1, 0), (0, 1), (-1, 0), (0, -1)]
|
|
|
|
i_order = 0
|
2013-11-05 19:39:03 +01:00
|
|
|
length = 1
|
|
|
|
a[y][x] = number
|
|
|
|
while not (x == (n-1) and y == 0):
|
|
|
|
for j in xrange(0, length):
|
2015-11-20 23:12:22 +01:00
|
|
|
xAdd, yAdd = order[i_order]
|
2013-11-05 19:39:03 +01:00
|
|
|
x += xAdd
|
|
|
|
y += yAdd
|
|
|
|
number += 1
|
|
|
|
a[y][x] = number
|
2015-11-20 23:12:22 +01:00
|
|
|
if x == (n-1) and y == 0:
|
2013-11-05 19:39:03 +01:00
|
|
|
break
|
2015-11-20 23:12:22 +01:00
|
|
|
if i_order == 1 or i_order == 3:
|
2013-11-05 19:39:03 +01:00
|
|
|
length += 1
|
2015-11-20 23:12:22 +01:00
|
|
|
i_order = (i_order+1) % 4
|
2013-11-05 19:39:03 +01:00
|
|
|
return a
|
|
|
|
|
2015-11-20 23:12:22 +01:00
|
|
|
|
|
|
|
def diagonal_sum(a):
|
2013-11-05 19:39:03 +01:00
|
|
|
n = len(a)
|
2015-11-20 23:12:22 +01:00
|
|
|
sum = -1 # you will have the element in the middle (1) twice
|
2013-11-05 19:39:03 +01:00
|
|
|
for i in xrange(0, n):
|
|
|
|
sum += a[i][i]
|
|
|
|
sum += a[n-i-1][i]
|
|
|
|
return sum
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import argparse
|
2015-11-20 23:12:22 +01:00
|
|
|
|
2013-11-05 19:39:03 +01:00
|
|
|
parser = argparse.ArgumentParser(description="ProjectEuler: 28")
|
|
|
|
parser.add_argument("-n", metavar='N', type=int,
|
|
|
|
help="length of the spiral", required=True)
|
2015-11-20 23:12:22 +01:00
|
|
|
parser.add_argument("-d", action="store_true", default=False,
|
2013-11-05 19:39:03 +01:00
|
|
|
help="display the spiral")
|
|
|
|
args = parser.parse_args()
|
|
|
|
array = initialise(args.n)
|
2015-11-20 23:12:22 +01:00
|
|
|
array = spiral_fill(array)
|
2013-11-05 19:39:03 +01:00
|
|
|
if args.d:
|
2015-11-20 23:12:22 +01:00
|
|
|
print_arr(array)
|
|
|
|
print diagonal_sum(array)
|