문제(출처: 프로그래머스)

PROGRAMMERS-962 행성에 불시착한 우주비행사 머쓱이는 외계행성의 언어를 공부하려고 합니다. 알파벳이 담긴 배열 spell과 외계어 사전 dic이 매개변수로 주어집니다. spell에 담긴 알파벳을 한번씩만 모두 사용한 단어가 dic에 존재한다면 1, 존재하지 않는다면 2를 return하도록 solution 함수를 완성해주세요.

 

▶ 내가 푼 방식

function solution(spell, dic) {
    var answer = 0;
    const spellLength = spell.length
    const newDic = dic.filter(i=> i.length == spellLength)
    answer = newDic.filter(word =>{
        let count = 0
        spell.forEach( i => word.includes(i) ? count +=1 : 0)
        if (count === spellLength) return word
    });
    return answer.length === 0 ? 2 : 1
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(spell, dic) {
    return dic.some(s => spell.sort().toString() == [...s].sort().toString()) ? 1 : 2;
}

// 유저 2
function solution(spell, dic) {
    return dic.filter(v=>spell.every(c=>v.includes(c))).length ? 1 : 2;
}

 

 배운 것들

     - array.some( ) : 배열의 요수 중 () 안에 주어진 함수를 적어도 하나라도 만족하면 true를 반환 하나도 통과 못하면 false를 반환

     - array.every( ) : 배열의 모든 요소가 () 안에 주어진 함수를 만족하면 true, 하나라도 만족을 못하면 false 를 반환 

+ Recent posts