Solutions to Advent of Code 2017 https://adventofcode.com/2017/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

03.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import math
  2. with open('data/03.txt', 'r') as file:
  3. square = int(file.readline().strip())
  4. # The maximum number in each ring in the spiral is 1, 9, 25, 49, 81, etc
  5. ring = math.ceil((math.sqrt(square)+1)/2.)
  6. # Calculate the numbers at the cardinal points (N/E/S/W) for that ring
  7. cardinals = [4*ring**2 - 11*ring + 8, 4*ring**2 - 9*ring + 6, 4*ring**2 - 7*ring + 4, 4*ring**2 - 5*ring + 2]
  8. # Distance "around" is the smallest difference between the input and one of the cardinals
  9. around = min(abs(c - square) for c in cardinals)
  10. # Plus the distance "inwards" is ring - 1
  11. print(f'Part one: {around+ring-1}')
  12. # There's no sensible way to calculate part two, and I can't be bothered writing
  13. # something to generate the sequence after I spent so much time avoiding doing that
  14. # for part one, so ¯\_(ツ)_/¯
  15. print('Part two: See table at https://oeis.org/A141481')
  16. # Bits of working:
  17. # Ring --> Max
  18. # 1 1
  19. # 2 9
  20. # 3 25
  21. # 4 49
  22. # n (n+(n-1))^2 ==> (2n-1)^2
  23. # m = (2n-1)^2
  24. # sqrt(m) = 2n-1
  25. # (sqrt(m)+1)/2 = n
  26. # https://oeis.org/A054552
  27. # 197 196 195 194 193 192 191 190 189 188 187 186 185 184 183
  28. # 198 145 144 143 142 141 140 139 138 137 136 135 134 133 182
  29. # 199 146 101 100 99 98 97 96 95 94 93 92 91 132 181
  30. # 200 147 102 65 64 63 62 61 60 59 58 57 90 131 180
  31. # 201 148 103 66 37 36 35 34 33 32 31 56 89 130 179
  32. # 202 149 104 67 38 17 16 15 14 13 30 55 88 129 178
  33. # 203 150 105 68 39 18 5 4 3 12 29 54 87 128 177
  34. # 204 151 106 69 40 19 6 1 2 11 28 53 86 127 176
  35. # 205 152 107 70 41 20 7 8 9 10 27 52 85 126 175
  36. # 206 153 108 71 42 21 22 23 24 25 26 51 84 125 174
  37. # 207 154 109 72 43 44 45 46 47 48 49 50 83 124 173
  38. # 208 155 110 73 74 75 76 77 78 79 80 81 82 123 172
  39. # 209 156 111 112 113 114 115 116 117 118 119 120 121 122 171
  40. # 210 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  41. # 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
  42. # Ring --> Key points
  43. # 1 1, 1, 1, 1
  44. # 2 2, 4, 6, 8
  45. # 3 11, 15, 19, 23
  46. # 4 28, 34, 40, 46