Skip to content

Instantly share code, notes, and snippets.

@krishicks
Created July 27, 2011 02:11
Show Gist options
  • Save krishicks/1108524 to your computer and use it in GitHub Desktop.
Save krishicks/1108524 to your computer and use it in GitHub Desktop.
yet another mars rover solution, this time using bit shifting and a hash that maps between squares of two and x,y coordinates
# lines 3..14 create a hash with squares of 2 pointing at their
# associated x,y coordinates as well as the inverse
width = 5
left = []
width.times { |i| left += [i] * (width + 1) } # [0,0,0,0,0,1,1,1,1,1..]
right = [*0..width] * width # [0,1,2,3,4,5,0,1,2,3,4,5..]
tuples = right.zip left # [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [0, 1], [1, 1]..
squares = [0] + (1..(width*width)).inject([]) { |acc,i| acc << 2**i } # [0, 2, 4, 8, 16, 32, 64, 128, 256, 512..
h = Hash[squares.zip tuples] # {0=>[0, 0], 2=>[1, 0], 4=>[2, 0], 8=>[3, 0]..
h.merge! h.invert
f = %w{ N E S W }
c = [ width+1, 1, -(width+1), -1 ]
bitrover = ->(binary_digit, dir, str) {
initial = c[f.index(dir)]
a = str.split('').inject(initial) { |amount, s|
case s
when 'L' then c[c.index(amount) - 1]
when 'R' then c[c.index(amount) - 3]
else binary_digit = binary_digit << amount; amount
end
}
p "#{h[binary_digit].join(' ')} #{f[c.index(a)]}"
}
bitrover[h[[1,2]], "N", "LMLMLMLMM"] # 1 3 N
bitrover[h[[3,3]], "E", "MMRMMRMRRM"] # 5 1 E
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment