- [소프티어] GPT식 숫자 비교2025년 01월 22일 16시 55분 04초에 업로드 된 글입니다.작성자: do_hyuk
https://softeer.ai/practice/11001
Softeer - 현대자동차그룹 SW인재확보플랫폼
softeer.ai
해당 문제는 정렬 문제로 쉽다고 생각할 수 있지만 특정 조건들 때문에 복잡하다고 느꼇고, 커스텀 정렬을 구현해야해서 시간이 걸렸다.
문제
일반적인 비내림차순 정렬일 경우 sort() 메서드 한 번이면 되겠지만 아래와 같은 조건들 때문에 커스텀 정렬을 구현함
[조건]
1. 소수점을 기준으로 x,y로 나누어 x1과 x2의 값이 같을 경우, y1과 y2의 크기로 정렬한다.
ex) 1.11 과 1.3 인 경우 1.11 > 1.3 이다.
2. 소수점이 없는 경우 x의 값이 같으면 소수점이 있는 수가 더 크다
ex) 1 과 1.0 인 경우 1 < 1.0 이다.
정렬 코드
// [커스텀 정렬 방식] // 반환값이 양수면 두 숫자의 위치를 변경 // 반환값이 음수면 위치 변경 없음 result.sort((a, b) -> { String[] aParts = a.split("\\."); String[] bParts = b.split("\\."); // 정수부분 길이 비교 int intComp = Integer.compare(aParts[0].length(), bParts[0].length()); if (intComp != 0) return intComp; // 정수부분이 같은지 비교 intComp = aParts[0].compareTo(bParts[0]); if (intComp != 0) return intComp; // 두 숫자의 소수점 존재 여부 boolean aHasFraction = (aParts.length == 2); boolean bHasFraction = (bParts.length == 2); // 소수점 여부로 정렬 if(aHasFraction && !bHasFraction) return 1; if(!aHasFraction && bHasFraction) return -1; // 소수점이 있으면 Y값을, 그렇지 않다면 -1 int aFraction = aHasFraction ? Integer.parseInt(aParts[1]) : -1; int bFraction = bHasFraction ? Integer.parseInt(bParts[1]) : -1; // 소수점 부분 크기 비교 return Integer.compare(aFraction, bFraction); });
이번에 거의 처음으로 삼항식과 compare 및 compareTo 메서드를 써보면서 편리함도 알았지만 가독성이 그리 좋지 않다는 것도 알았다. 다음에는 검색하는거 없이 직접 삼항식 및 Comparable 메서드 사용할 수 있도록 익숙해져야겠다.
전체 코드
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int N = Integer.parseInt(br.readLine()); List<String> result = new ArrayList<>(); for (int n=0; n<N; n++) { result.add(br.readLine()); } result.sort((a, b) -> { String[] aParts = a.split("\\."); String[] bParts = b.split("\\."); int intComp = Integer.compare(aParts[0].length(), bParts[0].length()); if (intComp != 0) return intComp; intComp = aParts[0].compareTo(bParts[0]); if (intComp != 0) return intComp; boolean aHasFraction = (aParts.length == 2); boolean bHasFraction = (bParts.length == 2); if(aHasFraction && !bHasFraction) return 1; if(!aHasFraction && bHasFraction) return -1; int aFraction = aHasFraction ? Integer.parseInt(aParts[1]) : -1; int bFraction = bHasFraction ? Integer.parseInt(bParts[1]) : -1; return Integer.compare(aFraction, bFraction); }); for(String num : result){ bw.write(num); bw.newLine(); } bw.flush(); bw.close(); } }
'코딩문제' 카테고리의 다른 글
[소프티어] 징검다리 (0) 2025.01.24 [소프티어] 성적평균 (1) 2025.01.23 [백준] 퇴사 - 14501 (0) 2025.01.10 [백준] N과 M (4) - 15652 (0) 2025.01.09 [백준] 큐2 - 18258 (0) 2025.01.09 댓글