알고리즘 97 - Take a Ten Minute Walk

jabae·2021년 11월 4일
0

알고리즘

목록 보기
97/97

Q.

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

A)

function isValidWalk(walk) {
  let desArr = [0, 0];
  
  for (let direct of walk) {
    if (direct === 'n') desArr[0]++;
    else if (direct === 's') desArr[0]--;
    else if (direct === 'w') desArr[1]++;
    else desArr[1]--;
  }
  
  return (walk.length === 10 && desArr[0] === 0 && desArr[1] === 0);
}

other

객체로 각각 방향을 key로 만들어 놓은 후,.forEach()로 방향마다 Value를 늘려주고 비교하는 방법도 있다.

function isValidWalk(walk) {
  var res = {n:0, w:0, s:0, e:0};
  walk.forEach((c) => res[c]++);
  return walk.length === 10 && res.n == res.s && res.e == res.w;
}
profile
it's me!:)

0개의 댓글