Problem
- You live in the city of Cartesia where all roads are laid out in a perfect grid.
- 당신은 모든 도로가 완벽한 격자(grid)에 배치된 Cartesia city에 살고 있다.
- You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk.
- 약속에 10분 일찍 도착해서 잠시 걷기로 했다.
- 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’]).
- 이 city는 시민들에게 Walk Generating App을 제공한다.
- 버튼을 누를 때마다 걷는 방향을 나타내는 하나의 문자열 배열이 전송된다.
- [‘n’, ‘s’, ‘w’, ‘e’] (North, South, West, East)
- You always walk only a single block in a 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 and will return you to your starting point.
- 하나의 block을 통과하는 데 1분이 걸린다.
- 출발점으로 돌아가는 데 10분이 걸리면 ‘true’를 반환한다.
- Return ‘false’ otherwise.
Solution 01
function isValidWalk(arr) {
const north = arr.filter((i) => i === 'n').length;
const south = arr.filter((i) => i === 's').length;
const west = arr.filter((i) => i === 'w').length;
const east = arr.filter((i) => i === 'e').length;
return arr.length === 10 && north === south && west === east;
}
isValidWalk(['n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n']); // false
isValidWalk(['n', 'n', 'n', 'n', 'n', 's', 's', 's', 's', 's']); // true
isValidWalk(['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 's']); // true
isValidWalk(['n', 'e', 's', 'w', 'n', 'w', 's', 'e', 's', 'n']); // true
isValidWalk(['n']); // false
Solution 02
function isValidWalk(arr) {
let distanceY = 0;
let distanceX = 0;
for (let i = 0; i < arr.length; i++) {
switch(arr[i]) {
case 'n':
distanceY++;
break;
case 's':
distanceY--;
break;
case 'w':
distanceX--;
break;
case 'e':
distanceX++;
break;
}
}
return arr.length === 10 && distanceY === 0 && distanceX === 0;
}
isValidWalk(['n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n']); // false
isValidWalk(['n', 'n', 'n', 'n', 'n', 's', 's', 's', 's', 's']); // true
isValidWalk(['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 's']); // true
isValidWalk(['n', 'e', 's', 'w', 'n', 'w', 's', 'e', 's', 'n']); // true
isValidWalk(['n']); // false
Solution 03
function isValidWalk(arr) {
let obj = {
n: 0,
s: 0,
w: 0,
e: 0
};
arr.forEach((i) => obj[i]++);
return arr.length === 10 && obj.n === obj.s && obj.w === obj.e;
}
isValidWalk(['n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'n']); // false
isValidWalk(['n', 'n', 'n', 'n', 'n', 's', 's', 's', 's', 's']); // true
isValidWalk(['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 's']); // true
isValidWalk(['n', 'e', 's', 'w', 'n', 'w', 's', 'e', 's', 'n']); // true
isValidWalk(['n']); // false