배열의 유사도
https://school.programmers.co.kr/learn/courses/30/lessons/120903
1차 - 입력을 다 안받아버리는 오류가…
배열 길이를 3이라고 입력을 하면, 코드만 본다면 원소를 3개를 받아야 하는데, 입력을 2개만 받아버리는 어이없는 상황이 발생했다.
package programmers.배열의_유사도;
import java.util.*;
public class arrayOverlap {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("첫 번째 배열의 길이를 입력하세요: ");
int a = scanner.nextInt();
String[] str1 = new String[a];
if (a > 100 || a < 1) {
System.out.println("배열의 길이는 1부터 100까지 가능합니다.");
}
System.out.println("첫 번째 배열의 원소(들)를 입력하세요: ");
for (int i = 0; i < str1.length; i++) {
str1[i] = scanner.nextLine();
}
for (int i = 0; i < a; i++) {
if (str1[i].length() > 10 || str1[i].length() < 1) {
System.out.println("원소의 길이는 1부터 10까지 가능합니다.");
}
for (int j = i + 1; j < a; j++) {
if (str1[i].equals(str1[j])) {
System.out.println("원소 중복 불가");
}
}
}
System.out.println("두 번째 배열의 길이 입력하세요: ");
int b = scanner.nextInt();
String[] str2 = new String[b];
if (b > 100 || b < 1) {
System.out.println("배열의 길이는 1부터 100까지 가능합니다.");
}
System.out.println("두 번째 배열의 원소(들)를 입력하세요: ");
for (int i = 0; i < b; i++) {
str2[i] = scanner.nextLine();
}
for (int i = 0; i < b; i++) {
if (str2[i].length() > 10 || str2[i].length() < 1) {
System.out.println("원소의 길이는 1부터 10까지 가능합니다.");
for (int j = i + 1; j < b; j++) {
if (str2[i].equals(str2[j])) {
System.out.println("원소 중복 불가");
}
}
}
int lenCompare = a > b ? 1 : 0;
int count = 0;
if (lenCompare == 1) {
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
if (str1[i].equals(str2[j])) {
count++;
}
}
}
} else {
for (int i = 0; i < b; i++) {
for (int j = 0; j < a; j++) {
if (str2[i].equals(str1[j])) {
count++;
}
}
}
}
System.out.println("result: " + count);
}
}
실행결과
그러나, 컴퓨터는 잘못한게 없다. 전부 다 내가 코드를 잘못 입력한 탓이다.
스캐너에서 scanner.nextInt(); 를 하고 엔터를 칠 경우에는 엔터 이전까지 값을 넘겨줘버려서 엔터가 버퍼에 남아있다.
그렇기 때문에 원소를 두개만 입력해도 컴퓨터는 엔터 또한 원소로 인식해버리기에,
사용자가 입력하려 했던 3번째 원소까지 입력받지 않고 넘겨버린 것!
💡 해결책
scanner.nextLine()은 엔터를 칠 때, 엔터키까지 같이 넘겨줘버려서 버퍼에 남아있는 엔터키는 없다.
그런데 nextLine()은 String용이기 때문에, 정수를 입력받을 우리를 위해 스캐너를 Integer.parseInt로 처리해주자.
즉, Integer.parseInt(scanner.nextLine());으로 입력받으면 해결 완료~
또한, 예외처리(배열 길이)를 통과해야 배열생성이 가능하도록 설계해야하므로 배열 생성은 예외처리 이후로 빼주자.
예외 처리를 통과하지 못한 경우에도 다음 문장을 실행하는 일이 일어나지 않도록 return을 추가해주자.
2차 - 실행은 되는데, 너ㅓ무 친절해버린 코드
package programmers.배열의_유사도;
import java.util.*;
public class arrayOverlap {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("첫 번째 배열의 길이를 입력하세요: ");
int a = Integer.parseInt(scanner.nextLine());
if (a > 100 || a < 1) {
System.out.println("배열의 길이는 1부터 100까지 가능합니다.");
return;
}
String[] str1 = new String[a];
System.out.println("첫 번째 배열의 원소(들)를 입력하세요: ");
for (int i = 0; i < str1.length; i++) {
str1[i] = scanner.nextLine();
}
for (int i = 0; i < a; i++) {
if (str1[i].length() > 10 || str1[i].length() < 1) {
System.out.println("원소의 길이는 1부터 10까지 가능합니다.");
}
for (int j = i + 1; j < a; j++) {
if (str1[i].equals(str1[j])) {
System.out.println("원소 중복 불가");
}
}
}
System.out.println("두 번째 배열의 길이 입력하세요: ");
int b = Integer.parseInt(scanner.nextLine());
if (b > 100 || b < 1) {
System.out.println("배열의 길이는 1부터 100까지 가능합니다.");
}
String[] str2 = new String[b];
System.out.println("두 번째 배열의 원소(들)를 입력하세요: ");
for (int i = 0; i < b; i++) {
str2[i] = scanner.nextLine();
}
for (int i = 0; i < b; i++) {
if (str2[i].length() > 10 || str2[i].length() < 1) {
System.out.println("원소의 길이는 1부터 10까지 가능합니다.");
}
for (int j = i + 1; j < b; j++) {
if (str2[i].equals(str2[j])) {
System.out.println("원소 중복 불가");
}
}
}
int lenCompare = a > b ? 1 : 0;
int count = 0;
if (lenCompare == 1) {
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
if (str1[i].equals(str2[j])) {
count++;
}
}
}
} else {
for (int i = 0; i < b; i++) {
for (int j = 0; j < a; j++) {
if (str2[i].equals(str1[j])) {
count++;
}
}
}
}
System.out.println("result: " + count);
}
}
실행결과:
프로그래머스는 알아서 값을 입력해주므로 사용자의 입력 처리를 굳이 내가 해줄 필요는 없었다. 그러므로, 조금 더 액기스만 뽑아보자.
3차 - 최종이라 생각했는데
변수명도 예쁘게 바꿔보았다.
아무튼 중요 알고리즘은,
두 배열의 길이를 비교해서 더 큰 배열을 기준으로 잡는다.
긴 배열의 기준 원소와 짧은 배열의 원소들을 비교해가며 그 둘이 같은 경우에는
답의 갯수에 1을 더해주는 그러한 알고리즘이 되시겠다.
package programmers.배열의_유사도.sol;
public class Main {
public static void main(String[] args) {
String[] s1 = { "a", "b", "c" };
String[] s2 = { "com", "b", "d", "p", "c" };
Solution sol = new Solution();
System.out.println(sol.solution(s1, s2));
}
}
class Solution {
public int solution(String[] s1, String[] s2) {
int answer = 0;
int lenCompare = s1.length > s2.length ? 1 : 0;
if (lenCompare == 1) {
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s1[i].equals(s2[j])) {
answer++;
}
}
}
} else {
for (int i = 0; i < s2.length; i++) {
for (int j = 0; j < s1.length; j++) {
if (s2[i].equals(s1[j])) {
answer++;
}
}
}
}
return answer;
}
}
실행 결과는 단순, 2 !!
어라 근데 굳이 두 배열의 길이를 비교할 필요가 있을까...?
2주후에 이걸 작성하다가 문득 생각이 들었다.
4차 - 찐찐최종
package programmers.배열의_유사도.sol;
public class Main {
public static void main(String[] args) {
String[] s1 = { "com", "b", "d", "p", "c" };
String[] s2 = { "a", "b", "c" };
Solution sol = new Solution();
System.out.println(sol.solution(s1, s2));
}
}
class Solution {
public int solution(String[] s1, String[] s2) {
int answer = 0;
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s1[i].equals(s2[j])) {
answer++;
}
}
}
return answer;
}
}
결국 나는 axb를 할지, bxa를 할지를 결정하기 위해 두 배열의 길이를 비교했던 것이다.
axb이나, bxa이나 결과는 똑같은데 말이다~^^^^…..하하
아무튼 발전스러운 과제였다~~
'JAVA > 코드 과제' 카테고리의 다른 글
[JAVA] 스타트와 링크 (백준 14889번) (0) | 2023.04.01 |
---|---|
[JAVA] OX퀴즈( ' 문자열 수식 배열 '의 참/거짓 결과 반환하기) (2) | 2023.03.05 |
[JAVA] 유한소수 판별하기 (0) | 2023.02.22 |
[JAVA] 자릿수 더하기 (0) | 2023.02.21 |
[JAVA] 최빈값 구하기 (0) | 2023.02.20 |