License Public Domain
Lines 68
Keywords
Euler28 (8)
Permissions
Owner: brianoneill
Group Owner: SnortSnort
Viewable by Everyone
Editable by brianoneill
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

Project Euler 28: Wacky Python Solution Atom Feed 0

# 's
 1########################################################################
2#
3# Project Euler #28
4#
5########################################################################
6
7import numpy as np
8
9size = 1001
10i=0
11j=1
12pos=1
13neg=-1
14########################################################################
15#
16# Spiral matrix is series of concentric boxes each formed by
17# counting through a series of four steps, each one more
18# diabolical than the last:
19# down the right side, left across the bottom,
20# up the left side, right across the top
21#
22# step() does each of those steps
23########################################################################
24
25def step(iorj,sign):
26 global coord,spiral,num,length,i,j
27 k = 1
28 num+=1
29 spiral[coord[i],coord[j]] = num
30 while k < length-1:
31 coord[iorj] += sign
32 num += 1
33 spiral[coord[i],coord[j]] = num
34 k += 1
35 return
36
37
38spiral = np.empty([size,size])
39
40spiral[size/2,size/2] = 1 ### center square is 1
41coord = [size/2,size/2+1] ### indices of next element to be updated
42length = 3
43num = 1
44########################################################################
45#
46# Form spiral matrix from inside out.
47########################################################################
48
49while length <= size:
50
51 step(i,pos) ### step down
52 coord[j] -= 1 ### left one
53 step(j,neg) ### step left
54 coord[i] -= 1 ### up one
55 step(i,neg) ### step up
56 coord[j] += 1 ### right one
57 step(j,pos) ### step right
58 coord[j] += 1 ### right one
59
60 length += 2
61
62
63print spiral
64########################################################################
65#
66# Summ up diagonal elements, account for double counting center square
67########################################################################
68summ = -1
69i = 0
70while i < size:
71 summ += spiral[i,i]
72 i += 1
73i = size - 1
74j = 0
75while j < size:
76 summ += spiral[i,j]
77 i -= 1
78 j += 1
79print summ

Comments

over 3 years ago (20 Feb 2013 at 05:15 PM) by jsimones
Oh boy, this is dirty. I need a shower after reading this.