GPT에게 문제를 만들어 달라했다.
문제 1: 연령별로 사람 정렬
각 사람이 이름과 나이를 포함하는 std::pair<std::string, int>로 표시되는 사람 목록이 주어지면 목록을 나이별로 오름차순으로 정렬하는 함수를 작성하세요. 두 사람의 나이가 같으면 이름을 알파벳순으로 정렬해야 합니다.
void sortPeopleByAge(std::vector<std::pair<std::string, int>>& people);
void sortPeopleByAge(std::vector<std::pair<std::string, int>>& people)
{
sort(people.begin(), people.end(), [](pair<string, int> a, pair<string, int> b)
{
if (a.second == b.second)
{
return a.first < b.first;
}
else
{
return a.second < b.second;
}
});
}
문제 2: 거리별로 포인트 정렬하기
2D 평면에 점의 벡터가 제공됩니다. 여기서 각 점은 (x, y) 좌표에 해당하는 std::pair<int, int>로 표시됩니다. 원점 (0, 0)으로부터의 거리가 오름차순으로 점을 정렬하는 함수를 작성하세요. 이 계산에는 유클리드 거리를 사용하지만, 비교에 필요한 경우가 아니면 제곱근 연산을 수행할 필요가 없습니다.
void sortByDistance(std::vector<std::pair<int, int>>& points)
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <utility>
#include <cmath>
void sortByDistance(std::vector<std::pair<int, int>>& points)
{
std::sort(points.begin(), points.end(), [](std::pair<int, int> a, std::pair<int, int> b)
{
return sqrt(pow(a.first - 0, 2) + pow(a.second - 0, 2) < sqrt(pow(b.first - 0, 2) + pow(b.second - 0, 2)));
});
}
int main() {
std::vector<std::pair<int, int>> points = { {1,2},{4,5},{6,7},{3,4},{3,7},{5,6},{6,1} };
sortByDistance(points);
return 0;
}
내가 푼 방법
유클리드 공식을 사용 하였다
sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
피타고라스와 유사하다. 추가) pow(a,b) b는 a를 얼만큼 제곱 하는지 이다. , sqrt는 루트
a.first - 0 : 0을 뺄 필요는 없지만 유클리드 공식을 떠올리기 위해 넣었다.
GPT에게 정답을 물어보니
void sortByDistance(std::vector<std::pair<int, int>>& points)
{
std::sort(points.begin(), points.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b)
{
// No need to take the square root for comparison, removed sqrt
return pow(a.first, 2) + pow(a.second, 2) < pow(b.first, 2) + pow(b.second, 2);
});
}
sqrt(루트)를 할 필요가 없다 어차피 거리값을 구하는게 아니라 거리 비교이기 때문에
'개인 공부 복습 > 알고리즘' 카테고리의 다른 글
| 완주하지 못한 선수 (해시) (0) | 2024.02.04 |
|---|---|
| 폰켓몬 (해시) (0) | 2024.02.04 |
| H-Index (정렬) (0) | 2024.02.04 |
| 가장 큰 수 ( 정렬) (0) | 2024.02.04 |
| K번째수 (정렬) (0) | 2024.02.03 |