Skip to content

Instantly share code, notes, and snippets.

@cmaitchison
Last active December 14, 2015 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmaitchison/5133520 to your computer and use it in GitHub Desktop.
Save cmaitchison/5133520 to your computer and use it in GitHub Desktop.
mars rover problem in 3 lines of ruby 2 code
IO.read('i').lines.drop(1).each_slice(2){|p,t|x,y,h=p.split;x,y,h=[x.to_i,y.to_i,h.to_sym];z={N:[->{y+=1},:W,:E],E:[->{
x+=1},:N,:S],S:[->{y-=1},:E,:W],W:[->{x-=1},:S,:N]};t.strip.split(//).map{|c|if c=='M';z[h][0].call;elsif c=='L';h=
z[h][1];else;h=z[h][2];end};puts"#{x} #{y} #{h}"}
@cmaitchison
Copy link
Author

i (the input file)

5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

@cmaitchison
Copy link
Author

output

1 3 N
5 1 E

@cmaitchison
Copy link
Author

There is some fat to trim, but I'm pretty sure it's not going to get down to 2 lines of code, using the almost_sinatra benchmark of a line of code being max 120 chars.

@cmaitchison
Copy link
Author

Updated to as small as I'm going to get it today.

@cmaitchison
Copy link
Author

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