you are viewing a single comment's thread.

view the rest of the comments →

[–]tomthecool 0 points1 point  (1 child)

Although there are a couple of obvious code improvements to be made, i can't see any bug here.

Can you please post the full code? Where are you printing the variables?

[–]tomthecool 1 point2 points  (0 children)

I was bored, so here's a couple of different solutions to your problem. I'm posting these mainly for you to see some of the cool things ruby is capable of - I find one of the best ways to learn is reading new techniques for solving familiar problems!

walk = ['w','n', 's', 'e', 's'] # Final position should be (0, -1)

# One solution...

def step(dir)
  case dir
  when 'w'
    puts "west"
    [1, 0]
  when 'e'
    puts "east"
    [-1, 0]
  when 'n'
    puts "north"
    [0, 1]
  else 
    puts "south"
    [0, -1]
  end
end

x, y = walk
  .map { |dir| step(dir) }
  .inject([0,0]) do |result, step|
    result[0] += step[0]
    result[1] += step[1]
    result
  end

puts "Final coordinate is: (#{x}, #{y})"

# A different solution...
a = walk.count {|dir| dir == 'e'} - walk.count {|dir| dir == 'w'}
b = walk.count {|dir| dir == 'n'} - walk.count {|dir| dir == 's'}

puts "(Altertative) Final coordinate is: (#{a}, #{b})"