본문 바로가기

코딩테스트

[Codewar] Take a Ten Minute Walk - 자바스크립트

문제 :

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!).

 

n,s,w,e라는 방향이 주어지고, 한 칸을 이동하는데 1분이 걸리며, 딱 10분까지 출발한 지점으로 돌아와야한다. 

 

function isValidWalk(walk) {
  var dx = 0
  var dy = 0
  var dt = walk.length

  for (var i = 0; i < walk.length; i++) {
    switch (walk[i]) {
      case 'n': dy--; break
      case 's': dy++; break
      case 'w': dx--; break
      case 'e': dx++; break
    }
  }

  return dt === 10 && dx === 0 && dy === 0
}

북쪽으로 이동한만큼, 남쪽으로 이동해야하며, 

서쪽으로 이동한만큼, 동쪽으로 이동해야한다. 

그래서 x축이든, y축이든 결국에 이동한 값은 0이 되어야 하며, 

결국에 움직인 시간이 10분일 때 true값을 반환하도록 한다.