princeofsudan

Project Euler#28 Number spiral diagonals

Mar 17th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. #Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
  2.  
  3. #21 22 23 24 25
  4. #20  7  8  9 10
  5. #19  6  1  2 11
  6. #18  5  4  3 12
  7. #17 16 15 14 13
  8.  
  9. #It can be verified that the sum of the numbers on the diagonals is 101.
  10.  
  11. #What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
  12.  
  13. def moveR(row,col,times):
  14.     for i in range(1,times+1):
  15.         arr[row][col+1] = arr[row][col] + 1
  16.         col += 1
  17.  
  18. def moveD(row,col,times):
  19.     for i in range(1,times+1):
  20.         arr[row+1][col] = arr[row][col] + 1  
  21.         row += 1
  22.  
  23. def moveL(row,col,times):
  24.     for i in range(1,times+1):
  25.         arr[row][col-1] = arr[row][col] + 1  
  26.         col -= 1
  27.  
  28. def moveU(row,col,times):
  29.     for i in range(1,times+1):
  30.         arr[row-1][col] = arr[row][col] + 1  
  31.         row -= 1
  32.        
  33.  
  34. dim = 1001
  35. arr = []
  36.  
  37. #Create an array of None elements
  38. for i in range(dim):
  39.     row = []
  40.     for j in range(dim):
  41.         row.append(None)
  42.     arr.append(row)
  43.  
  44. row = dim/2
  45. col = dim/2
  46. startValue = 1    
  47. arr[row][col] = startValue #Starting Position
  48.  
  49. for j in range(1,dim+1):
  50.  
  51.     if row == 0 and col == 0:
  52.         moveR(row,col,dim-1)
  53.         col += j
  54.     elif j%2 != 0:
  55.         moveR(row,col,j)
  56.         col += j
  57.         moveD(row,col,j)
  58.         row += j
  59.     elif j%2 == 0:
  60.         moveL(row,col,j)
  61.         col -= j
  62.         moveU(row,col,j)
  63.         row -= j
  64.  
  65.  
  66. count = 0
  67. for i in range(dim):
  68.     for j in range(dim):
  69.         if i == j or i+j == dim-1:
  70.             count += arr[i][j]
  71.            
  72. print count
Advertisement
Add Comment
Please, Sign In to add comment