[프로그래머스] A로 B 만들기

stella·2023년 1월 8일
0

Algorithm

목록 보기
5/40
post-thumbnail

문제

문자열 beforeafter가 매개변수로 주어질 때, before의 순서를 바꾸어 after를 만들 수 있으면 1을, 만들 수 없으면 0을 return 하도록 solution 함수를 완성해보세요.


1. 처음 생각한 로직

  • string으로 되어있는 beforeafter 를 array로 바꾼다.
    const beforeSort = [...before]
    const afterSort = [...after]

  • 비교하기 편하도록 before after 배열을 오름차순으로 정렬한다.

function solution(before, after) {
    const beforeSort = [...before].sort();
    const afterSort = [...after].sort();
       
    console.log(beforeSort);
    console.log(afterSort);
}

  • 정렬된 두 배열을 비교해서 서로 값이 같으면 return 1, 값이 다르면 return 0 을 한다
function solution(before, after) {
    const beforeSort = [...before].sort();
    const afterSort = [...after].sort();
    
    if (beforeSort === afterSort) {
        return 1;
    } else {
        return 0;
    }    
}

제출을 했는데 오답이 나왔다.

찾아보니 자바스크립트의 모든 것은 객체이고, 배열 또한 객체이기 때문에 두 배열을 비교할 때 서로 값을 비교하는 것이 아니라 해당 배열의 참조를 체크하기 때문이다.

따라서 두 배열의 값을 서로 비교하기 위해서는, 오름차순으로 정렬한 배열을 다시 문자열로 변환해주면 두 배열을 문자 그대로 비교할 수 있게 된다.

2. 오름차순으로 정렬된 배열을 다시 문자열로 변환해 값들을 비교해보자.

function solution(before, after) {
    const beforeSort = [...before].sort().join('');
    const afterSort = [...after].sort().join('');
    
    console.log(beforeSort);
    console.log(afterSort);
    
    if (beforeSort === afterSort) {
        return 1;
    } else {
        return 0;
    }    
}

다시 문자열로 변환했더니 두 배열의 값들을 그대로 비교해주는 것을 확인할 수가 있다.

profile
Frontend Engineer

0개의 댓글