Skip to content

Instantly share code, notes, and snippets.

@kmurph73
Last active December 31, 2017 19:34
Show Gist options
  • Save kmurph73/8e06922c5a4406a9464d4970cfdee2ae to your computer and use it in GitHub Desktop.
Save kmurph73/8e06922c5a4406a9464d4970cfdee2ae to your computer and use it in GitHub Desktop.
whiteboard wednesday spiral solution
require 'byebug'
spiral_arr = [
[1,2,3,4],
[5,6,7],
[8,9,10,11],
[12,13,14]
]
@held_arr = nil
@dirs = [:right, :down, :left, :up]
@dirNum = 0
@currentDir = @dirs[@dirNum]
@result = []
def turnRight
if @dirNum == @dirs.length - 1
@dirNum = 0
else
@dirNum += 1
end
@currentDir = @dirs[@dirNum]
end
def goRight(arr)
while arr[0].any?
@result.push arr[0].shift
end
arr.shift
turnRight()
spiral(arr)
end
def goDown(arr)
arr.each do |a|
@result.push a.pop
end
turnRight()
spiral(arr)
end
def goLeft(arr)
while arr[-1].any?
@result.push arr[-1].pop
end
# remove last array
arr.pop
turnRight()
spiral(arr)
end
def goUp(arr)
arr.reverse.each do |a|
@result.push a.shift
end
turnRight()
spiral(arr)
end
def spiral(arr)
# create a copy of array so we dont munge the original
@held_arr = Array.new(arr) if !@held_arr
if arr.empty?
return @result
else
case @currentDir
when :right
goRight(@held_arr)
when :down
goDown(@held_arr)
when :left
goLeft(@held_arr)
when :up
goUp(@held_arr)
end
end
end
expected_result = [1,2,3,4,7,11,14,13,12,8,5,6,10,9]
r = spiral(spiral_arr)
if r == expected_result
puts 'you wun'
else
puts 'YOU BLEW IT'
puts "expected: #{expected_result}"
puts "result: #{r}"
end
@kmurph73
Copy link
Author

kmurph73 commented Oct 25, 2017

coding interview practice competition w/ friends ... was done as quickly as possible to beat them. sorry for the camelCase, clearly had been doing too much CoffeeScript at the time

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