r/adventofcode • • Dec 03 '17

SOLUTION MEGATHREAD -🎄- 2017 Day 3 Solutions -🎄-

--- Day 3: Spiral Memory ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handy† Haversack‡ of Helpful§ Hints¤?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

21 Upvotes

297 comments sorted by

View all comments

1

u/APLtooter Dec 04 '17

APL [GNU]

∇steps←TAXI n
  r←r-0=2|r←⌊n*.5
  vert←-horz←.5×r-1
  ring←n-r*2
  sides←⌊ring÷1+r
  rem←(1+r)|ring
  step←0<ring
  path←horz,vert,step,((-step), 0 0 0)+(1 ¯1 ¯1 1)×4↑(sides⍴1+r),rem
  steps←+/|+⌿4 2⍴8↑path
∇

EVN←{2-⍨2×⍵}
ODD←{1-⍨2×⍵}
SHELL←{8×⍵}
BACK←{-(SHELL ⍵)↑0,(SHELL ⍵)⍴((ODD ⍵)⍴1),2}
FORW←{(2↓(SHELL ⍵)⍴0),1 1}
PREV←{(SHELL ⍵)⍴2,((ODD ⍵-1)⍴3),2 1}
ROT←{¯2⌽∊(0 1 2 3×EVN ⍵)+4⍴⊂(1-⍨⍳ODD ⍵-1),3⍴(ODD ⍵-1)}

∇sum←SPIRAL n
  core←(1)(1 2 4 5 10 11 23 25)
  r←2
loop:
  a←0⍴0
  inner←{+/(⍵[1])↑(1↓⍵)}¨⊂[2](PREV r),⊃{⍵⌽∊¯1↑core}¨ROT r
  ⊣{a←a,inner[⍵[3]]+(+/⍵[2]↑a)++/⍵[1]↑a}¨⊂[2](BACK r),(FORW r),⍪⍳(SHELL r)
  core←core,⊂a
  r←1+r
  sum←(<\(∊core)>n)/∊core
  →loop×⍬≡sum
∇

⍝ INPUT is a number
TAXI INPUT                      ⍝ Part 1
SPIRAL INPUT                    ⍝ Part 2

2

u/Porges Dec 04 '17 edited Dec 04 '17

Clunky Dyalog APL solution:

{ n←⍵ ⋄ arr←{(⌽(×/⍴⍵)+⍳⊃⍴⍵)⍪⌽⍉⍵}⍣{n∊⍺}⍪1 ⋄ x←|⌊(arr[1;]⍳n)-((2⌷⍴arr)÷2) ⋄ y←⌊((1⌷⍴arr)÷2) ⋄ x+y }

The spiral generation is kind of fun:

{(⌽(×/⍴⍵)+⍳⊃⍴⍵)⍪⌽⍉⍵}⍣{n∊⍺}⍪1

⍪1 take an array consisting of just '1'
{...}⍣{n∊⍺} ... until `n` is in the array,
  ⌽⍉⍵ rotate the array clockwise, then
    ⍳⊃⍴⍵ generate an array of the numbers from 1..'number of rows'
    (×/⍴⍵)+ offset those numbers by the number of items in the array (product of number of rows and columns),
    ⌽ reverse the numbers
  ⍪ and concatenate them to the top of the array

Then the rest of it is working out the x/y offset based on the fact that the number must be in the top row.

I'm much happier with my Part 2 solution:

{n←⍵ ⋄ {⌊/(⍵>n)/⍵} , {row ← ⍵[1;] ⋄ ⊖⍉ (+\ (1↓row, 0) + row + (0, ¯1↓row)) ⍪ ⍵} ⍣ {∨/ ,⍺>n} ⍪1}