본문 바로가기
코테 준비(with 프로그래머스)

프로그래머스 day6 - 마지막 두 원소

by jeong11 2023. 11. 11.
반응형
문제 설명

정수 리스트 num_list 주어질 , 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.

입출력 예
numLog result
[2,1,6] [2,1,6,5]
[5,2,1,7,5] [5,2,1,7,5,10]

입출력 예 #1
마지막 원소인 6이 그전 원소인 1보다 크기 때문에 6 - 1인 5를 추가해 return합니다.

입출력 예 #2
마지막 원소인 5가 그전 원소인 7보다 크지 않기 때문에 5의 두 배인 10을 추가해 return합니다.

 

접근을 잘못해서 헤맸었는데 

처음 뻘짓은 다음과 같았다 

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = {};
        
        for(int i=0; i<num_list.length; i++) {
            if(num_list[num_list.length-1] > num_list[num_list.length-2] ) {
                answer[num_list.length] += num_list[num_list.length-1] - num_list[num_list.length-2];
            } else {
              answer[num_list.length] += num_list[num_list.length-1]*num_list[num_list.length-1];
            }
        }
        
        return answer;
    }
}

=> 이렇게 뻘짓을 하면 ArrayIndexOutOfBoundsException 에러가 난다 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 0
at Solution.solution(Unknown Source)
at SolutionTest.lambda$main$0(Unknown Source)
at SolutionTest$SolutionRunner.run(Unknown Source)
at SolutionTest.main(Unknown Source)

 

=> 에러 원인 : 

자바는 배열의 작성 및 조작을 데이터 구조로 지원합니다. 

배열의 크기를 n이라고 했을 때 배열의 인덱스는 1부터 n까지가 아닌 0부터 n-1까지입니다. 

프로그래밍 중 ArrayIndexOutOfBoundsException이 가장 많이 발생하는 이유 중 하나로, 인덱스가 배열의 크기보다 크거나 음수 인덱스에 대한 요청이 있으면 자바는 위의 예외를 발생시킵니다.

 

 


 

 

*해결을 위해 이클립스에서 돌린 코드

eclipse에서 class를 하나 만들고 run in main으로 돌려보았다 

 

코드 수정 :

1. 전체 for문을 돌릴 필요가 없었다 

2. list 말고 정수의 경우 코드를 어떻게 만들어야 할까에 대한 코드를 짜보았다 -> 이걸 바탕으로 답을 작성한다 

    public int[] solution(int[] num_list) {
        int[] answer = {};

        int A=1;
        int B=6;

        if(A < B) {
              answer = B - A;

        } else if(A > B) {
              answer = B * 2;
        }

        return answer;
    }

3. int[] answer 배열을 만들어주었다

int[] answer = new int[num_list.length+1];

 

 

main.java

public class main {

    public static void main(String args[]) {	
            int[] test = new int[]{5,2,1,7,5};	
            System.out.println(Arrays.toString(solution5(test)));
    }

    public static int[] solution5(int[] num_list) {

        int[] answer = new int[num_list.length+1];
        int tmp = 0;
		
        //그전 원소
        int A = num_list[num_list.length - 2 ] ;
        //마지막 원소
        int B = num_list[num_list.length - 1 ];

        if(B > A) {
            tmp = B - A;
        } else{
            tmp = B * 2;
        }
		
        //마지막 원소의 뒤에 추가
        for(int i=0; i<num_list.length; i++) {
            answer[i] = num_list[i];
        }
        answer[answer.length-1] = tmp;

        return answer;
    }

}

정답

 

 

*내가 해결한 정답 코드 

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length+1];
        int tmp = 0;

        int A = num_list[num_list.length - 2 ] ;
        int B = num_list[num_list.length - 1 ];

        if(B > A) {
            tmp = B - A;
        } else{
            tmp = B * 2;
        }

        for(int i=0; i<num_list.length; i++) {
            answer[i] = num_list[i];
        }

        answer[answer.length-1] = tmp;

        return answer;
    }
}

 

 

반응형