Take a Ten Minute Walk ( 6 kyu )

문제

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 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!).

동서남북으로 걸어서 출발점으로 돌아올 수 있는지 확인하는 문제, 걸음이 너무 짧거나 길면 false를 리턴

풀이

function isValidWalk(walk) {
  if ( walk.length > 10 || walk.length < 3 ) return false;
  let obj = { 'e': 0, 'w': 0, 's': 0, 'n': 0 };
  for ( let i in walk ) {
    obj[walk[i]]++
  }
  return obj['e'] === obj['w'] && obj['s'] === obj['n'] ? true : false;
}

우선 예외처리를 가장 윗줄에서 해주고

obj 객체로 동서남북을 카운트해서 동,서의 개수와 남,북의 개수가 같으면 true 리턴

다른 사람의 풀이

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
}

스위치문으로 신기하게 풀어서 가져옴. 접근법은 크게 다르지 않은 듯 하다


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25
IQ Test ( 6 kyu )  (0) 2017.11.24
Duplicate Encoder ( 6 kyu )  (0) 2017.11.23
Stop gninnipS My sdroW! ( 6 kyu )  (0) 2017.11.22

+ Recent posts