문제자체도 어렵지만, 그 과정속에서 삽질한 과정이 있어서 정리해두려한다.

문제

첫줄에 입력하는 수만큼의 단어를 입력받아 글자수가 작은것부터 오름차순으로 정렬하고, 첫 알파벳이 같다면 알파벳순으로 정렬하는 문제이다. 당연히 중복도 배제해야한다.

문제의 코드

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(reader.readLine());
        //단어(문자열)을 담은 배열 strAry
        List<String> strAry = new ArrayList<>();
        //각 단어의 길이를 담는 배열 strLength
        List<Integer> strLength = new ArrayList<>();

        for(int i = 0 ; i < N ; i++){
            String str = reader.readLine();
            if(!strAry.contains(str)){//중복 단어 제거. 만약 리스트에 입력값이 존재하지 않다면
                strAry.add(i, str);
                strLength.add(i, str.length());
            }
        }//for end

        for(int i = 0 ; i < strAry.size()-1 ; i++){
            if(strLength.get(i) > strLength.get(i+1)){//앞선 단어가 뒤의 단어보다 길다면
                String temp1 = strAry.get(i);
                String temp2 = strAry.get(i+1);
                System.out.println(temp1 + " " + temp2);
                int lTemp1 = strLength.get(i);
                int lTemp2 = strLength.get(i+1);

                strAry.add(i, temp2);
                strAry.add(i+1, temp1);

                strLength.add(i, lTemp2);
                strLength.add(i+1, lTemp1);
            }//if end
        }//for end

		..........미완성..........

    }//main end
}//class end

문제를 모두 푼 상태는 아니다.(나중에 풀이는 또 올릴게요ㅠ)

무한루프에 빠져버려서 원인을 못찾고 있었는데, 생각해보니까 예전에도 비슷한 방식으로 무한루프에 빠진적이 있어서 제대로 원인을 찾아보았다.

문제 & 해결

for(int i = 0 ; i < strAry.size()-1 ; i++){
            if(strLength.get(i) > strLength.get(i+1)){//앞선 단어가 뒤의 단어보다 길다면
                String temp1 = strAry.get(i);
                String temp2 = strAry.get(i+1);
                System.out.println(temp1 + " " + temp2);
                int lTemp1 = strLength.get(i);
                int lTemp2 = strLength.get(i+1);

                strAry.add(i, temp2);
                strAry.add(i+1, temp1);

                strLength.add(i, lTemp2);
                strLength.add(i+1, lTemp1);
            }//if end
        }//for end

해당 부분에서 무한루프가 발생했다.
처음에는 단지 i번 값과 i+1번 값을 비교해서 위치를 바꾸는 식으로 진행했는데

strAry.add(i, temp2);
&
strAry.add(i+1, temp1);

실제로 리스트의 원소 위치를 바꾸는 대신, 단순히 새로운 원소를 리스트에 추가하기만 한다.
strAry.add(i, temp2);
strAry.add(i+1, temp1);

호출은 기존의 원소들을 대체하는 것이 아니라, 해당 인덱스에 새 원소를 삽입하고 기존 원소들을 뒤로 밀어내는 동작을 수행한다.
그 결과 리스트의 길이가 계속해서 증가하게 되어 무한 루프에 빠지게 되는것이였다.


List의 개념과 각각의 메서드들에 대한 더 깊은 학습이 필요하다고 생각한다...

0개의 댓글