ALGORITHM/소프티어(Softeer)
[소프티어] 8단 변속기 - Java
Doraemon_lulu
2024. 10. 31. 15:56
문제는 다음과 같다.
알고보니 Arrays.equals()를 활용하여 배열의 요소를 비교하는 간단한 문제였는데, 처음에는 너무 복잡하게 돌아갔다.
테스트는 전체 통과했으나, 너무 복잡해서 정석적인(?) 방법으로 다시 풀어봤다.
Arrays.equals 관련 참고 자료: https://docs.oracle.com/javase/8/docs/api/index.html
우선 처음 접근했던 방식은 아래의 코드와 같다.
- Queue 클래스를 활용하여 숫자 요소들을 앞뒤로 비교했다. 이 때 Ascending의 패턴이면 1로 설정하고 Descending의 패턴이면 -1으로 설정하여 Ascending/Descending/Mixed를 구분하고자 했다.
- Stream의 allMatch 메서드를 활용하여 최종 패턴을 구분하고 결과값을 도출해내도록 했다.
import java.io.*;
import java.util.*;
public class Main {
private static final int COUNT = 8;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Queue<Integer> q = new LinkedList<>();
for(int i = 0; i < COUNT; i++) {
q.offer(Integer.parseInt(input.split(" ")[i]));
}
List<Integer> checkNum = new ArrayList<>();
for (int i = 0; i < COUNT-1; i++) {
// 두번째 숫자 - 첫번째 숫자
int prevNum = q.poll();
if(q.peek() - prevNum > 0) {
checkNum.add(1);
} else {
checkNum.add(-1);
}
}
String result = "mixed";
boolean checkAscending = checkNum.stream().allMatch(s -> s.equals(1));
boolean checkDescending = checkNum.stream().allMatch(s -> s.equals(-1));
if (checkAscending == true) {
result = "ascending";
} else if(checkDescending == true) {
result = "descending";
}
System.out.println(result);
}
}
좀 복잡하게 풀어내기는 했지만...
덕분에 Queue에서 활용할 수 있는 기본적인 메서드들(offer, poll, peek 등)을 사용해 볼 수 있었고, 더불어 Stream의 allMatch도 한번 활용해 볼 수 있는 좋은 경험이 된 것 같다. :)
다른 방법을 찾아보니, 이미 Ascending 및 Descending 패턴은 지정되어 있기에 int 배열로 미리 설정해두고 배열끼리 비교하도록 할 수 있었다.
- ascending 및 descending 패턴을 가진 int 배열을 임의로 선언 및 초기화해주었다.
- 반환할 결과를 우선 mixed로 초기화해주었다.
- 입력받은 패턴을 int 배열로 생성해주고, 패턴을 Arrays.equals를 통해 비교했다.
import java.io.*;
import java.util.*;
public class Main {
private static final int COUNT = 8; // 숫자 8개
public static void main(String[] args) {
String result = "mixed";
int[] ascending = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
int[] descending = new int[]{8, 7, 6, 5, 4, 3, 2, 1};
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int[] nums = new int[8];
for(int i = 0; i < COUNT; i++) {
nums[i] = Integer.parseInt(input.split(" ")[i]);
}
if (Arrays.equals(nums, ascending)) {
result = "ascending";
} else if (Arrays.equals(nums, descending)) {
result = "descending";
}
System.out.println(result);
}
}