Skip to content

Instantly share code, notes, and snippets.

@bcjordan
Last active April 29, 2016 17:19
Show Gist options
  • Save bcjordan/7326767 to your computer and use it in GitHub Desktop.
Save bcjordan/7326767 to your computer and use it in GitHub Desktop.
Spiral Traversal problem solutions
  • Bernie Margolis in Java (gist)
  • Florent Crivello in Objective-C (gist)
  • Srismil Dutta in Javascript (gist)
  • Eran Zimbler in Javascript (gist and node.js module)
  • Maurin Lenglart in Javascript (gist)
  • Ankit Goyal in Ruby (gist, imgur clean notes, original notes)
  • Kevin Le Brun in Python (with a nice writeup and tests!) (gist), who accurately notes "I saw a typo in the second test case for the problem. You should replace '194' with '14'."
  • C is for Conrad Meyer (another C solution) (gist)
  • Péter Ferenczy in Ruby (utilizing lazy enumerators) (gist)
  • Srismil Dutta in Javascript (gist)
  • Scott Schulthess in Ruby (gist)
  • The Return of the Michael Penkov in Python (gist) (and neat HTML5 / python solutions for last week's problem (browser-viewable))
  • Kevin Wu in C++ (gist)
  • Alistair Burgsch (imgur), who says Sure it wouldn't compile... Missing parameter types, and various other missing labels, but basic premise is: Declare 2d array with the initial size, loop inner and outer to fill it. While loop to loop through X*Y elements Test the current position for bounds of array, populating the output array if position valid. Advance the location by the stepsize in the appropriate direction, adding one to the step after left and down moves. https://db.tt/uznpzADz for my inside of an envelope solution ;-)

Problem:

Write a function that accepts four arguments. The first two arguments are the size of the grid (h x w), filled with ascending integers from left to right, top to bottom, starting from 1. The next two arguments are is the starting positions, the row (r) and column (c).

Return an array of integers obtained by spiraling outward anti-clockwise from the r and c, starting upward.

f(5, 5, 3, 3)

// Should return: 
// [ 13, 8, 7, 12, 17, 18, 19,
// 14, 9, 4, 3, 2, 1, 6,
// 11, 16, 21, 22, 23, 24,
// 25, 20, 15, 10, 5 ]

f(2, 4, 1, 2) // [ 2, 1, 5, 6, 7, 3, 8, 4 ]

The following graphics show the grid in question and the spiral generated, beginning at cell (3, 3).

Grid 1

Grid 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment