The Zits Code

Problem F - The Zits Code

Kudos to the writer for merging a comic reference [even including a pic of Jeremy at the start] - with a dig at Dan Brown.

Anyway, after question A this seemed the second most popular question, possibly as it tells you exactly what to do, the difficulty lies in finding a nice code-able way of doing it. The exact encryption scheme is given to you - use a square grid, spiral the message through it, pad the rest with '$', and return the grid read one row at a time.
Finding the size of the grid is simple - ceil(sqrt(size of input)) for those mathematically inclined, however it's safer and easier to calculate that with a loop - as is passing with '$' and forming the output, the tricky part left then is spiralling.

To see how it's done, look at the the sample 6x6 grid they give, and the path we take around it:
[using (0, 0) as the top left, and (5, 5) as the bottom right, as this is where they'd go in an array)
  1. At (0, 0), facing east, take 6 steps.
  2. At (0, 5), facing south, take 5 steps.
  3. At (5, 5), facing west, take 5 steps.
  4. At (5, 0), facing north, take 4 steps.
  5. At (1, 0), facing east, take 4 steps.
  6. At (1, 4), facing south, take 3 steps.
  7. At (4, 4), facing west, take 3 steps.
  8. At (4, 1), facing north, take 2 steps......etc.
The directions cycle east/south/west/north then back to east, etc.
The number of steps to take in that direction goes 6,5,5,4,4,3,3,2,...
Combining these together, we can spiral by keeping how many steps we are to take, and which direction we are going, then changing them in the patterns observed above.

(Untested) code that implements this can be found here.

Comments

Popular posts from this blog

Beans!

Sounds good - part 1

Comment Away!