💡 알파벳이 담긴 배열 spell과 외계어 사전 dic이 매개변수로 주어집니다. spell에 담긴 알파벳을 한번씩 모두 사용한 단어가 dic에 존재한다면 1, 존재하지 않는다면 2를 return 하도록 solution 함수를 완성해주세요.
입출력 예시
spell | dic | result |
---|---|---|
["p", "o", "s"] | ["sod", "eocd", "qixm", "adio", "soo"] | 2 |
["z", "d", "x"] | ["def", "dww", "dzx", "loveaw"] | 1 |
["s", "o", "m", "d"] | ["moos", "dzx", "smm", "sunmmo", "som"] | 2 |
function solution(spell, dic) {
let answer = 0;
let array = new Array(dic.length + 1).fill(0);
for (let i = 0; i < dic.length; i++) {
for (let j = 0; j < spell.length; j++) {
if (dic[i].includes(spell[j])) {
array[i]++;
}
array.includes(spell.length) ? (answer = 1) : (answer = 2)
}
}
return answer;
}
dic 배열의 길이보다 1 큰 배열 array를 만들어서 모든 요소를 0으로 초기화
let array = new Array(dic.length + 1).fill(0)
// [0,0,0,0,0] , dic=["def", "dww", "dzx", "loveaw"]
이중 for문으로 dic과 spell의 각 요소에 대해 반복. dic[i]에 spell[j] 요소가 포함 되어 있다면, array[i]의 값을 1 증가 시킴.
array 배열에 spell length의 길이와 같은 값이 있다면, 알파벳을 한번씩 모두 사용한 단어가 dic에 존재함을 의미. 1을 return.
for (let i = 0; i < dic.length; i++) {
for (let j = 0; j < spell.length; j++) {
if (dic[i].includes(spell[j])) {
array[i]++; // [1,1,3,0,0]
}
array.includes(spell.length) ? (answer = 1) : (answer = 2);
}
}
return answer;
some
활용
some() 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 적어도 하나라도 통과하면 true를 반환.
function solution(spell,dic) {
return dic.some((ele) => spell.sort().toString() === [...ele].sort().toString())
? 1
: 2;
}