관리 메뉴

기억을 위한 기록들

[Code Wars] Take a Ten Minutes Walk(C++) 본문

Coding Test - cpp/Etc

[Code Wars] Take a Ten Minutes Walk(C++)

에드윈H 2024. 1. 9. 09:05

https://www.codewars.com/kata/54da539698b8a2ad76000228/train/cpp

 

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

 

 

 


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.
약속 시간보다 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']).
그 도시는 시민들에게 휴대전화로 걷기 생성 앱을 제공합니다. 여러분이 버튼을 누를 때마다 걷기 위한 길을 나타내는 한 글자로 된 줄을 보내줍니다(예: ['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.
항상 글자(방향)마다 한 블록씩만 걸으며 한 도시 블록을 횡단하는 데 1분이 걸린다는 것을 알고 있으므로 앱에서 제공하는 걷기가 정확히 10분이 소요되며(일찍 또는 늦는 것을 원하지 않습니다!), 물론 출발점으로 되돌아갈 수 있는 기능을 만듭니다.

Return false otherwise.
그렇지 않으면 false를 반환합니다.

 

 

문제는 동서남북 4방향의 문자 배열로 안내되는데 10분안에 다시 출발지점으로 돌아와야한다.1칸당 1분이 소요된다고 한다.

입력값 예시 :

 

나의 풀이 : 

#include<vector>
#include<map>

int arr[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };

std::map<char, int> m = {
{'n',0},
{'s',1},
{'e',2},
{'w',3},
};


bool isValidWalk(std::vector<char> walk) {

	if (walk.size() == 10)
	{
		std::pair<int, int> location = { 0,0 };
		for (auto item : walk)
		{
			int num = m[item];
			location.first += arr[num][0];
			location.second += arr[num][1];
		}

		if (location.first == 0 & location.second == 0)
		{
			return true;
		}
	}

	return false;
}

 

 

난 2차원 배열과 map으로 4방향에 대한 값을 저장하고 그 방향에 따라 다시 원점으로 돌아오는지에 대해 생각해서 풀었는데 다른 사람의 풀이를 보고 살짝 허무했다. 엄청 짧게 해결한것이였다.

 

 

다른사람의 풀이 : 

bool isValidWalk(const std::vector<char>& walk) {
    return walk.size() == 10 &&
        std::count(begin(walk), end(walk), 'n') == std::count(begin(walk), end(walk), 's') &&
        std::count(begin(walk), end(walk), 'w') == std::count(begin(walk), end(walk), 'e');
}

 

단순히 사이즈 확인과 동서, 남북의 갯수가 서로 대응 되는지만 확인한 것이다..