https://www.codewars.com/kata/54da539698b8a2ad76000228
Codewars - Achieve mastery through coding practice and developer mentorship
A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
DESCRIPTION:
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!).
설명:
당신은 모든 도로가 완벽한 격자무늬로 설계된 Cartesia의 도시에 살고 있습니다. 당신은 약속 시간보다 10분 일찍 도착했기 때문에 잠깐 산책을 하기로 결정했습니다. 도시는 시민들에게 당신이 버튼을 누를 때마다 걷는 방향(예) ['n', 's', 'w', 'e'])을 나타 내는 한 글자의 문자열 배열을 보내주는 Walk Generating 앱을 제공합니다. 당신은 각 글자(방향) 마다 한 블록만을 걷고 한 도시 블록을 횡단하는데 1분이 걸린다는 것을 알고 있습니다. 만약 앱이 제공하는 도보가 정확히 10분(더 빠르거나 늦고 싶지 않습니다!)이면 -그리고 물론 당신은 시작 지점으로 돌아가야 합니다- true를 반환하는 함수를 만드세요. 그렇지 않은 경우 false를 반환하세요
참고: 항상 무작위의 방향 단어('n', 's', 'e', 또는 'w'만)의 모음을 포함한 유효한 배열을 받습니다. 빈 배열은 주어지지 않습니다 (그것은 걷는 것이 아니라 가만히 서있는 것입니다!).
풀이
원래 자리로 돌아오려면 북쪽으로 간 횟수와 남쪽으로 간 횟수, 서쪽으로 간 횟수와 동쪽으로 간 횟수가 같아야 한다. 그래서 n과 s, e와 w를 따로 체크해 n이라면 ns를 + 1 하고 s라면 ns를 - 1, e이라면 ew를 + 1 하고 w라면 ew를 - 1 해서 ns와 ew가 모두 0이라면 true를 그렇지 않다면 false를 반환했다. 그리고 정확히 10분이어야 하기 때문에 만약 주어진 배열의 길이가 10이 아니라면 false를 반환했다.
코드
function isValidWalk(walk) {
if(walk.length !== 10) return false;
let ns = 0;
let ew = 0;
for(let i = 0; i < walk.length; i++){
if(walk[i] === 'n') ns++;
if(walk[i] === 's') ns--;
if(walk[i] === 'e') ew++;
if(walk[i] === 'w') ew--;
}
if(ns !== 0 || ew !== 0) return false;
return true;
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Reversed Strings (8 kyu) / JavaScript (0) | 2022.11.28 |
---|---|
[Codewars] Grasshopper - Debug sayHello (8 kyu) / JavaScript (0) | 2022.11.26 |
[Codewars] Path Finder #1: can you reach the exit? (4 kyu) / JavaScript (0) | 2022.11.24 |
[Codewars] Shortest Word (7 kyu) / JavaScript (0) | 2022.11.23 |
[Codewars] Jaden Casing Strings (7 kyu) / JavaScript (0) | 2022.11.22 |
댓글